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

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

What does this line of code mean?

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

The ? and :

13条回答
  •  孤独总比滥情好
    2020-11-22 04:39

    This is the C ternary operator (Objective-C is a superset of C):

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

    is semantically equivalent to

    if(inPseudoEditMode) {
     label.frame = kLabelIndentedRect;
    } else {
     label.frame = kLabelRect;
    }
    

    The ternary with no first element (e.g. variable ?: anotherVariable) means the same as (valOrVar != 0) ? valOrVar : anotherValOrVar

提交回复
热议问题