Search code examples
iphoneiosnsstringif-statementstringwithformat

iOS: if-else within a stringwithformat


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" : 
                                                             @""];