Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLocalizedString with variables Swift

Tags:

ios

swift

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 file, should I have the following?

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

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

like image 202
netwire Avatar asked Oct 31 '14 23:10

netwire


2 Answers

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") 
like image 188
duan Avatar answered Oct 10 '22 23:10

duan


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) 
like image 45
r_19 Avatar answered Oct 11 '22 01:10

r_19