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.
\n\nExample
\n\nNSLog(@\"%1$@, %2$@\", @\"Red\", @\"Blue\");\nNSLog(@\"%2$@, %1$@\", @\"Red\", @\"Blue\");\n
\n\nOutput
\n\nRed, Blue\nBlue, Red\n
\n\nNote that the format string changed, but the parameters are in the same order.
\n","author":{"@type":"Person","name":"Avi"},"upvoteCount":16}}}Reputation: 7918
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];
Upvotes: 9
Views: 3837
Reputation: 2318
So your format specifier %1$@ %2$d means:
%1$@ for %@(Objective-C object) with first parameter and
%2$d for %d*(Signed 32-bit integer (int))* with second parameter.
This $0, $1, $2 are shorthand parameter names like in Closures
“Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.”
Upvotes: 1
Reputation: 7552
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.
Upvotes: 16