Please Help Me Intepret This Code SWIFT

前端 未结 4 566
遥遥无期
遥遥无期 2020-12-07 05:35
display.text = newValue != nil ? \"\\(newValue!)\" : \" \" 

Does the syntax of the code mean, let display.text = newValue, if it does not equal nil

相关标签:
4条回答
  • 2020-12-07 06:19

    Its a ternary operator. It is use for some condition. If condition is true then it execute the part after ? otherwise the part after :. In your case the condition is if newValue not equals to nil then unwrap it otherwise return empty string.

    0 讨论(0)
  • 2020-12-07 06:31

    From the documentation

    Ternary Conditional Operator

    The ternary conditional operator is a special operator with three parts, which takes the form question ? answer1 : answer2. It is a shortcut for evaluating one of two expressions based on whether question is true or false. If question is true, it evaluates answer1 and returns its value; otherwise, it evaluates answer2 and returns its value.

    The ternary conditional operator is shorthand for the code below:

    if question {
       answer1 
    } else {
       answer2
    }
    
    0 讨论(0)
  • 2020-12-07 06:33

    The answers about the ternary operator are correct.

    An alternative way to write this would be with the "nil-coalescing operator" ??:

    display.text = newValue ?? ""
    

    Which means if the value before ?? Is not nil, use that unwrapped value, else use the value after ??

    0 讨论(0)
  • 2020-12-07 06:37

    it means that

    if newValue == nil {
        display.text = " "
    } else {
        display.text = "(newValue!)"
    }
    

    if newValue is not nil, display.text will be (newValue!).

    if you want to show newValue's value,

    you should write that

    if newValue == nil {
        display.text = " "
    } else {
        display.text = "\(newValue!)"
    }
    
    0 讨论(0)
提交回复
热议问题