I've been working with format specifiers but they were generic like %d
or %@
but today in a tutorial I saw these %1$@%2$d
and didn't understand what they represent.
It was a calculator example so they are using them in this statement: stack = [NSString stringWithFormat:@"%1$@%2$d",stack,number];
The numbers represent positional parameters. The parameters which follow the format string are slotted into the string based on their position in the parameters list. The first parameter goes into the %1 slot, the second into the %2 slot, and so on. The purpose is to deal with languages where the order of terms/words/etc might change from your default. You can't change the parameter order at runtime, but you can make sure the parameters end up in the correct place in the string.
Example
NSLog(@"%1$@, %2$@", @"Red", @"Blue");
NSLog(@"%2$@, %1$@", @"Red", @"Blue");
Output
Red, Blue
Blue, Red
Note that the format string changed, but the parameters are in the same order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With