I\'m trying to figure out how to use NSLocalizedString with variables.
For example, if I want to output \"by Peter and Larry\", in my Localizable.strings
An example with the Localizable.strings file:
In Localizable.strings file:
localizable_text = "Title %@ (Code: %@)";
In Swift class:
let title = "Error"
let code = "123456"
let alertMessage = String(format: NSLocalizedString("localizable_text", comment: ""), title, code)
yes, you should have "account.by_user" = "by %@ and %@";
and take this:
let localizedString = NSLocalizedString("account.by_user", comment: "any comment")
let wantedString = String(format: localizedString, "Peter","Larry")
String(format: NSLocalizedString("Pick_Only", comment: ""), sectionData.max)
In Localizable.strings: "Pick_Only" = "Pick only %d";
This is another way and how I do it.
let myString = String.localizedStringWithFormat(NSLocalizedString("by %@ and %@", comment: "yourComment"), name1, name2)
basically, the main idea of Localized String with format is like this:
let math = "Math"
let science = "Science"
String.localizedStringWithFormat(NSLocalizedString("I love %@ and %@", comment: "loved Subjects"), math, science)
Adding a small sample below as it took me some time to figure the Localizable.strings file formatting.
Example of adding variables to localized string:
In code:
let myVar: String = "My Var"
String(format: NSLocalizedString("translated_key %@",
comment: "Comment"), myVar)
In Localizable.strings file:
"translated_key %@" = "My var is: %@";
Of course, the %@
on the right side can be replaced:
"translated_key %@" = "My var is: %@";
"translated_key %@" = "%@ is my var";
"translated_key %@" = "I use %@ as my var";
Also, %@
can be replaced by %d
for int or %f
for a float.