Swift: string formatting issues

I have an extension for String

func localized(table: String? = nil, bundle: Bundle = .main, args: CVarArg...) -> String {
  return String(
    format: NSLocalizedString(
      self,
      tableName: table,
      bundle: bundle,
      value: self,
      comment: ""
    ),
    args
  )
}

Localizable .line file:

"%d seconds ago" = "%d seconds ago";

Using:

print("%d seconds ago".localized(args: 5))
print(String.localizedStringWithFormat("%d seconds ago", 5))

And the result:

<some_random_number_here> seconds ago.
5 seconds ago.

Can someone explain to me what I'm doing wrong?

+4
source share
2 answers

String has two similar initializers:

init(format: String, _ arguments: CVarArg...)
init(format: String, arguments: [CVarArg])

The first takes a different number of arguments, the second an array with all arguments:

print(String(format: "x=%d, y=%d", 1, 2))
print(String(format: "x=%d, y=%d", arguments: [1, 2]))

In your method, it localized args: CVarArg...is a variable parameter and they become available inside the function body as an array of the assigned type, in this case [CVarArg]. Therefore, it must be transmitted String(format: arguments:):

func localized(table: String? = nil, bundle: Bundle = .main, args: CVarArg...) -> String {
  return String(
    format: NSLocalizedString(
      self,
      tableName: table,
      bundle: bundle,
      value: self,
      comment: ""
    ),
    arguments: args   // <--- HERE
  )
}

See also “Variation Options” in “Functions” in the Quick Link chapter.

+5

. args .

extension String {
    func localized(table: String? = nil, bundle: Bundle = .main, args: CVarArg...) -> String {
        return String(format: NSLocalizedString(self, tableName: table, bundle: bundle, value: self, comment: ""), args.first!)
    }
}

print("%d hey!".localized(args: 5))

,

(format: String, arguments: [CVarArg])

 print("%d %d hey!".localized(args: 5, 7))
0

Source: https://habr.com/ru/post/1662555/


All Articles