0

Scenario: I have a requirement in localization where I need to have values in a string irrespective of their order. An example could be considered as below:

1st language: {username} is {age} old.

2nd language Age {age} is of {username}.

Positional Specifier: To achieve this we have something called as positional specifiers. A discussion on this could be found here. I tried including positional specifiers in an example code as follows:

// Prints "Time is cruel"    
let output = String(format: "%1$@ %2$@ %3$@", "Time", "is", "cruel")

// Prints "Time" but ideally should print the 3rd argument i.e "cruel".
let output1 = NSString(format: "%3$@", "Time", "is", "cruel")

Is there a way to achieve the functionality above? Can it be done via positional specifiers and if can what am I missing?

G.Abhisek
  • 1,034
  • 11
  • 44
  • 2
    http://pubs.opengroup.org/onlinepubs/000095399/functions/fprintf.html: *"When numbered argument specifications are used, specifying the Nth argument requires that all the leading arguments, from the first to the (N-1)th, are specified in the format string."* – Martin R Aug 14 '18 at 07:06
  • 1
    https://stackoverflow.com/questions/34657641/nsstring-stringwithformat-less-parameters/34657997#34657997 – Martin R Aug 14 '18 at 07:07
  • Can you provide a concrete example where you would need this? Your username/age example uses 2 positional parameters in both languages. – Martin R Aug 14 '18 at 07:14
  • I have edited the question. That is the requirement but my approach to the problem via positional specifier is wrong. It is clear from your above comments and referred links. – G.Abhisek Aug 14 '18 at 07:18
  • 1
    I do not know of a built-in method, you probably have to make your own. That should not be too difficult if only the `%@` format is used. Compare https://stackoverflow.com/q/34546349/1187415 and https://stackoverflow.com/q/2946649/1187415 for possible approaches (that's Objective-C, but the same ideas can be used in Swift). – Martin R Aug 14 '18 at 07:23

0 Answers0