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

前端 未结 13 2222
南旧
南旧 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.
    

提交回复
热议问题