This is an idea on how to implement NSLocalizedString string localization in Swift.
Given the Localizable.strings
file:
"%@ loves %@" = "%2$@ ♥️ %1$@";
let personA = "Alice"
let personB = "Bob"
let localized = "\(personA) loves \(personB)."|~
results in:
localized = "Bob ♥️ Alice"
There are four alternatives for the infix notation:
let localized = "\(personA) loves \(personB)." |~ ()
… searches for the key "%@ loves %@" in Localizable.strings
of mainBundle()
.
let localized = "\(personA) loves \(personB)." |~ ("Flowerpower")
… searches for the key "%@ loves %@" in Flowerpower.strings
of mainBundle()
.
let bundle = NSBundle(identifier: "com.example.bundle")
let localized = "\(personA) loves \(personB)." |~ (bundle)
… searches for the key "%@ loves %@" in Localizable.strings
of the bundle with identifier com.example.bundle
.
let bundle = NSBundle(identifier: "com.example.bundle")
let localized = "\(personA) loves \(personB)." |~ ("Flowerpower", bundle)
… searches for the key "%@ loves %@" in Flowerpower.strings
of the bundle with identifier com.example.bundle
.
let localized = DHLocalizedString("\(personA) loves \(personB).")
… searches for the key "%@ loves %@" in Localizable.strings
of mainBundle()
.
let localized = DHLocalizedString("\(personA) loves \(personB).", tableName: "Flowerpower")
… searches for the key "%@ loves %@" in Flowerpower.strings
of mainBundle()
.
let bundle = NSBundle(identifier: "com.example.bundle")
let localized = DHLocalizedString("\(personA) loves \(personB).", bundle: bundle)
… searches for the key "%@ loves %@" in Localizable.strings
of the bundle with identifier com.example.bundle
.
let bundle = NSBundle(identifier: "com.example.bundle")
let localized = DHLocalizedString("\(personA) loves \(personB).", tableName: "Flowerpower", bundle: bundle)
… searches for the key "%@ loves %@" in Flowerpower.strings
of the bundle with identifier com.example.bundle
.
The operator |~
looks a bit like a flag.
In your Localizable.strings
file, replace all interpolations with %@
, regardless of the type of the interpolation. Do not use %@
as part of the key. You may use positional parameters in the translated string, as shown above.
See LICENSE for license information.