Chaudhry Talha
Chaudhry Talha

Reputation: 7918

What does this %1$@%2$d format specifier means in objective c

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

Answers (2)

Vitya Shurapov
Vitya Shurapov

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

Avi
Avi

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

Related Questions