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

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

What does this line of code mean?

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

The ? and :

相关标签:
13条回答
  • 2020-11-22 04:38

    Ternary operator example.If the value of isFemale boolean variable is YES, print "GENDER IS FEMALE" otherwise "GENDER IS MALE"

    ? means = execute the codes before the : if the condition is true. 
    : means = execute the codes after the : if the condition is false.
    

    Objective-C

    BOOL isFemale = YES;
    NSString *valueToPrint = (isFemale == YES) ? @"GENDER IS FEMALE" : @"GENDER IS MALE";
    NSLog(valueToPrint); //Result will be "GENDER IS FEMALE" because the value of isFemale was set to YES.
    

    For Swift

    let isFemale = false
    let valueToPrint:String = (isFemale == true) ? "GENDER IS FEMALE" : "GENDER IS MALE"
    print(valueToPrint) //Result will be  "GENDER IS MALE" because the isFemale value was set to false.
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 04:39

    Simply, the logic would be

    (condition) ? {code for YES} : {code for NO}

    0 讨论(0)
  • 2020-11-22 04:39

    It's just a short form of writing an if-then-else statement. It means the same as the following code:

    if(inPseudoEditMode)
      label.frame = kLabelIndentedRect;
    else
      label.frame = kLabelRect;
    
    0 讨论(0)
  • 2020-11-22 04:40

    It's the ternary or conditional operator. It's basic form is:

    condition ? valueIfTrue : valueIfFalse
    

    Where the values will only be evaluated if they are chosen.

    0 讨论(0)
  • 2020-11-22 04:40

    This is part of C, so it's not Objective-C specific. Here's a translation into an if statement:

    if (inPseudoEditMode)
        label.frame = kLabelIndentedRec;
    else
        label.frame = kLabelRect;
    
    0 讨论(0)
提交回复
热议问题