Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String with format from localized string

Tags:

ios

swift

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

like image 1000
CainaSouza Avatar asked Sep 01 '25 22:09

CainaSouza


1 Answers

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)
}
like image 105
rmaddy Avatar answered Sep 04 '25 02:09

rmaddy