display.text = newValue != nil ? \"\\(newValue!)\" : \" \"
Does the syntax of the code mean, let display.text = newValue, if it does not equal nil
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.
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 evaluatesanswer1
and returns its value; otherwise, it evaluatesanswer2
and returns its value.The ternary conditional operator is shorthand for the code below:
if question { answer1 } else { answer2 }
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 ??
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!)"
}