What does the question mark and the colon (?: ternary operator) mean in objective-c?

前端 未结 13 2429
南旧
南旧 2020-11-22 04:10

What does this line of code mean?

label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;

The ? and :

13条回答
  •  无人共我
    2020-11-22 04:20

    Fun fact, in objective-c if you want to check null / nil For example:

    -(NSString*) getSomeStringSafeCheck
    {
        NSString *string = [self getSomeString];
        if(string != nil){
            return String;
        }
        return @"";
    }
    

    The quick way to do it is:

    -(NSString*) getSomeStringSafeCheck
    {
        return [self getSomeString] != nil ? [self getSomeString] : @"";
    }
    

    Then you can update it to a simplest way:

    -(NSString*) getSomeStringSafeCheck
    {
        return [self getSomeString]?: @"";
    }
    

    Because in Objective-C:

    1. if an object is nil, it will return false as boolean;
    2. Ternary Operator's second parameter can be empty, as it will return the result on the left of '?'

    So let say you write:

    [self getSomeString] != nil?: @"";
    

    the second parameter is returning a boolean value, thus a exception is thrown.

提交回复
热议问题