What's NSLocalizedString equivalent in Swift?
I use next solution:
1) create extension:
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
2) in Localizable.strings file:
"Hi" = "Привет";
3) example of use:
myLabel.text = "Hi".localized
enjoy! ;)
--upd:--
for case with comments you can use this solution:
1) Extension:
extension String {
func localized(withComment:String) -> String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
}
}
2) in .strings file:
/* with !!! */
"Hi" = "Привет!!!";
3) using:
myLabel.text = "Hi".localized(withComment: "with !!!")
The NSLocalizedString
exists also in the Swift's world.
func NSLocalizedString(
key: String,
tableName: String? = default,
bundle: NSBundle = default,
value: String = default,
#comment: String) -> String
The tableName
, bundle
, and value
parameters are marked with a default
keyword which means we can omit these parameters while calling the function. In this case, their default values will be used.
This leads to a conclusion that the method call can be simplified to:
NSLocalizedString("key", comment: "comment")
Swift 5 - no change, still works like that.
A variation of the existing answers:
Swift 5.1:
extension String {
func localized(withComment comment: String? = nil) -> String {
return NSLocalizedString(self, comment: comment ?? "")
}
}
You can then simply use it with or without comment:
"Goodbye".localized()
"Hello".localized(withComment: "Simple greeting")
Please note that genstrings
won't work with this solution.