4

I am trying to display a localized string that contains an argument. Instead of displaying the string in one line with the argument embedded, the result is a broken 3-line string:

Expected result:

The price is $9.99/year.

Result:

The price is (
    "$9.99"
)/year.

Localizable.strings:

"price_string" = "The price is %@/year.";

Call:

"price_string".localized(priceString)

where priceString is a String variable.

And .localized() is defined as such:

extension String {
    var localized: String {
      return NSLocalizedString(self, comment: "\(self)_comment")
    }

    func localized(_ args: CVarArg...) -> String {
      return String(format: localized, args)
    }
}
Kqtr
  • 5,824
  • 3
  • 25
  • 32

1 Answers1

8

Please look at the output. It shows clearly that the price argument is an array. And indeed the variadic parameter args is treated as an array.

So you are just using the wrong API

func localized(_ args: CVarArg...) -> String {
     return String(format: localized, arguments: args)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thank you so much. I actually cannot get to the definition of that String initializers. I managed to find the one you suggest using (and it works): https://developer.apple.com/documentation/foundation/nsstring/1407827-init. But I can't find the doc for the initializer that I was using. – Kqtr May 21 '20 at 12:04
  • We are talking about Swift : https://developer.apple.com/documentation/swift/string/3126743-init – vadian May 21 '20 at 12:06
  • Oh indeed. So the one I was incorrectly using is: https://developer.apple.com/documentation/swift/string/3126742-init. I don't see any definition of what the init does/returns. Is it just that the documentation is incomplete, or are we supposed to understand this naturally? – Kqtr May 21 '20 at 12:09
  • Unfortunately many APIs in Swift seem to be incomplete. However the `String(format` APIs are actually self-explanatory. – vadian May 21 '20 at 12:15
  • All right. Thank you so much again for taking the time to explain all this! – Kqtr May 21 '20 at 12:22
  • I was using String(format: s, args) which also didn't work, String(format: s, arguments: args) did the job for me – Paulo Taylor Feb 17 '21 at 14:11
  • 1
    Thanks, this answer probably helped me save 30mins of further debugging work :D – DeveloBär Nov 09 '21 at 20:10