Reputation: 9
display.text = newValue != nil ? "\(newValue!)" : " "
Does the syntax of the code mean, let display.text = newValue, if it does not equal nil let it be an optional of newValue as a string or " ". This interpretation is a guess, any help that can be provided will be appreciated
Thank you
Upvotes: 0
Views: 95
Reputation: 150605
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 ??
Upvotes: 0
Reputation: 150
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!)"
}
Upvotes: 0
Reputation: 285079
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 }
Upvotes: 1
Reputation: 2451
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.
Upvotes: 1