CainaSouza
CainaSouza

Reputation: 1437

String with format from localized string

I have this function to display a localized text with parameters:

func displayLocalizedMessage(key: String, args: [CVarArg]) {
    someLabel.text = String.localizedStringWithFormat(NSLocalizedString(key, comment: ""), args)
}

If I call it passing two parameters, for example, notificationPostTagging as key and ["Joshua"] for args and the localized string is like this:

"notificationPostTagging" = "%@ tagged you in a post.";

I'm getting this printed in the app:

(
  Joshua
) tagged you in a post.

Does anyone have any idea how to fix this. I can't pass the second parameter as a comma-separated list because it comes from some other object.

Thanks

Upvotes: 4

Views: 2417

Answers (2)

Md. Shofiulla
Md. Shofiulla

Reputation: 2305

I also faced this kind of problem and after spending some hours I solved it with this line

textlabel.text = "my_string_key".localized(with: ["store_name"])

and my localized string like this Arabic

 "my_string_key" = "إذا كنت قد أجريت عملية شراء بالفعل ، فسيقوم %@ بإعلامنا بذلك.";

French

"my_string_key"="Si vous avez déjà effectué un achat, %@ nous en informera.";

This answer based on swift 5 or above

Upvotes: 0

rmaddy
rmaddy

Reputation: 318794

localizedStringWithFormat does not take an array of arguments, it takes a variable list of arguments. So when you pass args, it treats that array as only one argument. The %@ format specifier then converts the array to a string which results in the parentheses.

You should use the String initializer that takes the format arguments as an array.

func displayLocalizedMessage(key: String, args: [CVarArg]) {
    someLabel.text = String(format: NSLocalizedString(key, comment: ""), locale: Locale.current, arguments: args)
}

Upvotes: 8

Related Questions