Reputation: 643
I want to add an array of localized strings as datasource for a collection view in a swift application.
I have written this :
let text = [NSLocalizedString("s0",comment: ""),NSLocalizedString("s1",comment: ""),NSLocalizedString("s2",comment: ""),NSLocalizedString("s3",comment: ""),NSLocalizedString("s4",comment: ""),NSLocalizedString("s5",comment: ""),NSLocalizedString("s6",comment: ""),NSLocalizedString("s7",comment: ""),NSLocalizedString("s8",comment: "")]
Is there a more simple way to put all the strings in the array, because I have 1000 localized strings and this does not look right.
Upvotes: 3
Views: 4039
Reputation: 111
EDIT: Realized you could write this in two steps and not three. Simplified my answer.
public func Localized(_ key: String) -> String {
return NSLocalizedString(key, comment: "")
}
// for example
let localized = ["s0", "s1", "s2"].map { Localized($0) }
Upvotes: 4
Reputation: 4760
Alternatively you can do it like that:
HelperClass:
static func getLocalized(withKey key: String, targetSpecific:Bool) -> String{
if targetSpecific{
return NSLocalizedString(key, tableName:"TargetSpecific", comment: "")
}
else{
return NSLocalizedString(key, comment: "")
}
}
static func getLocalizedArray(withKey key: String, targetSpecific:Bool) -> [String]{
return getLocalized(withKey: key, targetSpecific: targetSpecific).components(separatedBy: ",")
}
Localizable.string
"optionsArray" = "Show devices,Add device";
So you can call it like that:
let optionsArray:[String] = AppHelper.getLocalizedArray(withKey: "optionsArray", targetSpecific: false)
Upvotes: 0
Reputation: 14237
You can always set your strings with a format (s%d.4 , for instance) and build your array around that format.
var text:NSMutableArray = NSMutableArray()
for index in 1...10 {
let formattedString = String(format: "s%.4d", index)
let localizedString = NSLocalizedString(formattedString, comment: "comment")
text.addObject(localizedString)
}
Then you declare your strings like: s0001, s0002, s0003, etc.
Upvotes: 1