一个由 Swift 宏驱动的包,简化了 iOS、macOS 和其他 Apple 平台应用程序中的字符串本地化。它提供了一种类型安全、可维护且优雅的方式,使用 Swift 枚举来处理本地化。
@Localizable
注解它import Localization
@Localizable
enum Strings {
case welcome(name: String)
case itemCount(count: Int)
case totalPrice(amount: Double)
}
let welcomeText = Strings.welcome(name: "John").localized
let itemCountText = Strings.itemCount(count: 5).localized
let priceText = Strings.totalPrice(amount: 99.99).localized
Localizable.strings
文件"welcome" = "Welcome, %@!";
"itemCount" = "You have %d items";
"totalPrice" = "Total: $%.2f";
通过 Swift Package Manager 将 Localization 添加到你的项目中
在 Xcode 中,前往 File > Swift Packages > Add Package Dependency。
输入仓库 URL
https://github.com/telemtobi/swift-localization.git
选择你喜欢的版本并完成。
你可以使用 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
为了使你的本地化字符串使用起来更加方便,你可以向 String
和 LocalizedStringKey
添加扩展。这允许更自然且对 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 文件。