2

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

CainaSouza
  • 1,417
  • 2
  • 16
  • 31
  • `args: [CVarArg])` seems strange to me. I would have expect something like: https://developer.apple.com/documentation/foundation/nspredicate/1414167-init or https://developer.apple.com/documentation/foundation/nspredicate/1417368-init – Larme Dec 14 '17 at 19:27
  • Possible solutions at https://stackoverflow.com/q/27914053/1187415 and https://stackoverflow.com/a/42457746/1187415 – Martin R Dec 14 '17 at 19:32

2 Answers2

5

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)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Hey @rmaddy, the string is still printed as I posted initially because this String initializer you posted uses `CVarArg...` as argument. I had to adapt it to use a second available initializer: `String(format: "Something %@", arguments: args) `. Thanks for showing that option. – CainaSouza Dec 14 '17 at 19:39
  • Yeah, I forgot to add the `arguments` label to the 3rd parameter. The answer is fixed. – rmaddy Dec 14 '17 at 19:43
0

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

Md. Shofiulla
  • 2,135
  • 1
  • 13
  • 19