Swift 本地化

一个由 Swift 宏驱动的包,简化了 iOS、macOS 和其他 Apple 平台应用程序中的字符串本地化。它提供了一种类型安全、可维护且优雅的方式,使用 Swift 枚举来处理本地化。

Swift SPM License

特性

快速开始

  1. 创建一个枚举并使用 @Localizable 注解它
import Localization

@Localizable
enum Strings {
    case welcome(name: String)
    case itemCount(count: Int)
    case totalPrice(amount: Double)
}
  1. 在你的代码中使用它
let welcomeText = Strings.welcome(name: "John").localized
let itemCountText = Strings.itemCount(count: 5).localized
let priceText = Strings.totalPrice(amount: 99.99).localized
  1. 将相应的键添加到你的 Localizable.strings 文件
"welcome" = "Welcome, %@!";
"itemCount" = "You have %d items";
"totalPrice" = "Total: $%.2f";

安装

Swift Package Manager

通过 Swift Package Manager 将 Localization 添加到你的项目中

  1. 在 Xcode 中,前往 File > Swift Packages > Add Package Dependency

  2. 输入仓库 URL

    https://github.com/telemtobi/swift-localization.git
    
  3. 选择你喜欢的版本并完成。

使用

键格式化

你可以使用 keyFormat 参数自定义枚举 case 如何转换为本地化键

@Localizable(keyFormat: .camelCase)
enum Strings { // Default: welcomeMessage -> "welcomeMessage"
    case welcomeMessage
}

@Localizable(keyFormat: .lowerSnakeCase)
enum Strings { // welcomeMessage -> "welcome_message"
    case welcomeMessage
}

@Localizable(keyFormat: .upperSnakeCase)
enum Strings { // welcomeMessage -> "WELCOME_MESSAGE"
    case welcomeMessage
}

使用关联值

枚举 case 中的关联值会自动映射到你的本地化字符串中的格式参数

@Localizable
enum Alerts {
    case deleteConfirmation(itemName: String)
    case syncProgress(completed: Int, total: Int)
}

// Localizable.strings
"deleteConfirmation" = "Are you sure you want to delete %@?";
"syncProgress" = "Synced %d out of %d items";

// Usage
let alert = Alerts.deleteConfirmation(itemName: "Document").localized
let progress = Alerts.syncProgress(completed: 5, total: 10).localized

字符串扩展

为了使你的本地化字符串使用起来更加方便,你可以向 StringLocalizedStringKey 添加扩展。这允许更自然且对 SwiftUI 友好的语法

extension String {
    static func localized(_ string: Strings) -> Self {
        string.localized
    }
}

extension LocalizedStringKey {
    static func localized(_ string: Strings) -> Self {
        .init(string.localized)
    }
}

现在,你可以以更优雅的方式使用你的本地化

label.text = .localized(.welcome(name: "John"))

Text(.localized(.welcome(name: "John")))

这种方法

要求

贡献

欢迎贡献!请随时提交 Pull Request。

许可证

本项目基于 MIT 许可证 - 有关详细信息,请参阅 LICENSE 文件。