I want to format a string, in Swift, with two potential arguments (using Format specifiers). The string to format may have a place for only the first argument, only the second argument, or both arguments. If I use the first or both arguments it works, but if I use only the second argument, it does not work. For instance:
let title = "M."
let name = "David"
let greetingFormat = "Hello %1$@ %2$@"
print(String(format: greetingFormat, title, name))
// OUTPUT> Hello M. David
// OK
If I use only the first argument in the String to format:
let greetingFormat = "Hello %1$@"
print(String(format: greetingFormat, title, name))
// OUTPUT> Hello M.
// OK
But when using only the second argument
let greetingFormat = "Hello %2$@"
print(String(format: greetingFormat, title, name))
// OUTPUT> Hello M.
// NOT THE EXPECTED RESULT!
In the last case I expected "Hello David". Is it a bug? How can I obtain the intended result for the last case where only the second argument is used?
Remarks:
- Please note that this problem occurs in the context of localization (i.e. the string to format comes from a Localizable.strings file), so I don’t have the possibility to remove unused argument directly.
- The question does not relate to person’s name formatting. This is just taken as a example.