NSLocalizedString with Swift Variables

I am trying to figure out how to use NSLocalizedString with variables.

For example, if I want to output "Peter and Larry" in my Localizable.strings file, should I have the following?

 "account.by_user" = "by %@ and %@"; 

How can I call NSLocalizedString("account.by_user", comment: "") with if there are 2 variables name1 and name2 where name1 = Peter and name2 = Larry?

+9
source share
4 answers

yes, you must 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") 
+13
source

This is a different way and how I do it.

 let myString = String.localizedStringWithFormat(NSLocalizedString("by %@ and %@", comment: "yourComment"), name1, name2) 

basically, the basic idea of ​​a Localized String with a format is like this:

 let math = "Math" let science = "Science" String.localizedStringWithFormat(NSLocalizedString("I love %@ and %@", comment: "loved Subjects"), math, science) 
+8
source

Adding a small sample below, since it took me a while to determine the formatting of the Localizable.strings file.

An example of adding variables to a localized string:

In code:

 let myVar: String = "My Var" String(format: NSLocalizedString("translated_key %@", comment: "Comment"), myVar) 

In the 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"; 

In addition, %@ can be replaced with %d for int or %f for float.

+4
source

Example with the file Localizable.strings:

In the Localizable.strings file:

 localizable_text = "Title %@ (Code: %@)"; 

In the Swift class:

 let title = "Error" let code = "123456" let alertMessage = String(format: NSLocalizedString("localizable_text", comment: ""), title, code) 
+2
source

Source: https://habr.com/ru/post/977572/


All Articles