iOS: if-else within a stringwithformat
-
15-04-2021 - |
Question
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.
Solution
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" :
@""];
OTHER TIPS
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" : @""];
NSString *myString = nil;
if (condition1) {
myString = [NSString stringWithFormat:@"%@", condition1];
} else {
myString = [NSString stringWithFormat:@"%@", condition2];
}
BOOL test =0;
NSString *string = [NSString stringWithFormat:@"%@%@", @"myString1", test? @"Mystriong 2":@"Mystring3"];
NSLog(@"string: %@", string);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow