iOS: if-else within a stringwithformat

1.4k Views Asked by At

I am an iOS newbie, so please bear with me.

I want to construct a string using stringWithFormat, but I want to put in a part of a string only if a condition is true. How would I achieve something like -

myString = [NSString stringWithFormat:@"%@%@", 
           @"myString1",
           //put myString2 only if (someCondition)]

Please let me know if I am not clear enough.

4

There are 4 best solutions below

0
Ben S On BEST ANSWER

The most legible way to do this would be to use an explict if block.

However, you can also do it inline with the ternary operator:

BOOL condition = YES;
NSString* str = [NSString stringWithFormat: @"%@%@", @"string1", 
                                                     (condition) ? 
                                                         @"string2" : 
                                                         @""];
1
Andreas On

One way to achieve that is to insert an empty string if the condition is false and use the second string is true like this:

myString = [NSString stringWithFormat:@"%@%@", @"myString1",
           (condition) ? @"This is myString2" : @""];
2
Bill Burgess On
NSString *myString = nil;
if (condition1) {
   myString = [NSString stringWithFormat:@"%@", condition1];
} else {
   myString = [NSString stringWithFormat:@"%@", condition2];
}
0
AAV On
    BOOL test =0;
NSString *string = [NSString stringWithFormat:@"%@%@", @"myString1", test? @"Mystriong 2":@"Mystring3"];
NSLog(@"string: %@", string);