TestsTested | ✓ |
LangLanguage | SwiftSwift |
License | MIT |
ReleasedLast Release | Apr 2017 |
SwiftSwift Version | 3.1 |
SPMSupports SPM | ✗ |
Maintained by sgr-ksmt.
i18n for Swift.
"order_view_title" = "Order"
"order_view_button" = "Order (price: %@)"
==========================
// "Order"
titleLabel.text = NSLocalizedString("order_view_title", comment: "")
// "Order (price: USD100.00)"
let price = "$100.00"
let buttonTitle = String(format: NSLocalizedString("order_view_button", comment: ""), arguments: price)
orderButton.setTitle(buttonTitle, for: .normal)
⬇️⬇️⬇️
// "Order"
titleLabel.text = i18n.t(.orderViewTitle)
// "Order (price: USD100.00)"
orderButton.setTitle(i18n.t(.orderViewButton, args: i18n.currencyISO(100)), for: .normal)
Localizable.strings
"hello_world" = "Hello, world!";
"total_count" = "Total: %d";
Add Localizable.strings
in your project and define keys and values.
LocalizedString
extension i18n.LocalizedString {
static let helloWorld: i18n.LocalizedString = "hello_world"
static let totalCount: i18n.LocalizedString = "total_count"
// or
static let helloWorld = i18n.LocalizedString(rawValue: "hello_world")
}
Add LocalizedString
's static variable as extension of i18n.LocalizedString
.
It's similar to Notification.Name
.
extension Notification.Name {
static let fooDidUpdate = Notification.Name(rawValue: "FooDidUpdate")
}
i18n
let message = i18n.t(.helloWorld)
print(message) // "Hello, world!
// localize and embed paramter(s)
let total = i18n.t(.totalCount, args: 100)
print(total) // "Total: 100"
Tips Add args:
label and parameter(s) if you can embed arguments in localized string.
i18nSwift equips function of changing the language in appllication.
If you change the language, result of localization will change.
// en
"greeting" = "Hello!";
// fr
"greeting" = "Bonjour!";
// system language is "en"
print(i18n.t(.greeting)) // "Hello!"
// Change language to "fr"
i18n.Language.current = "fr"
print(i18n.t(.greeting)) // "Bonjour!"
// ===================
// Reboot application!!
// ===================
// `Language.current` is being stored.
print(i18n.t(.greeting)) // "Bonjour!"
// Reset to system language
i18n.Language.reset()
// change temporary in localization
print(i18n.t(.greeting, "fr")) // "Bonjour!"
Tips : i18n.Language.current
is saved in UserDefaults using i18n.Language.Constant.currentLanguageKey
i18nSwift converts number into localized currency.
// default is `Locale.current`
print(i18n.currency(100)) // $100.00
print(i18n.currency(100, Locale(identifier: "ja_JP"))) // ¥100
print(i18n.currency(100, fractionDigits: (4, 4))) // $100.0000
print(i18n.currencyISO(100)) // USD100.00
Download all *.swift
files and put your project.
Change log is here.
i18nSwift is under MIT license. See the LICENSE file for more info.