When I'm using string formatting, can I access one parameter multiple times without passing it again?
Example:
NSString *parameter1 = @"1"; NSString *parameter2 = @"2"; NSString *myString; myString = [NSString stringWithFormat:@"I want to print parameter1 here: %@, parameter2 here: %@ and now access parameter1 again: %@ _without_ passing it again.",parameter1, parameter2, parameter1];
Is there a way to access the first parameter again without writing ", parameter1" again?
Yes, using positional arguments:
// prints: foo bar foo bar NSLog(@"%@", [NSString stringWithFormat:@"%2$@ %1$@ %2$@ %1$@", @"bar", @"foo"]); // NSLog supports it too NSLog(@"%2$@ %1$@ %2$@ %1$@", @"bar", @"foo");
NSString *parameter1 = @"1"; NSString *parameter2 = @"2"; NSString *myString; myString = [NSString stringWithFormat:@"I want to print parameter1 here: %1$@, parameter2 here: %2$@ and now access parameter1 again: %1$@ _without_ passing it again.",parameter1, parameter2];
String Format Specifiers
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