It essentially replaces the if...else
form.
So:
if shouldDecrease == false {
increase()
} else {
decrease()
}
becomes:
shouldDecrease ? decrease() : increase()
Where this is particularly useful is if an assignment is made within the if...else
branches.
So:
var number: Int = 0
if shouldDecrease == false {
number = number + 1 //or number += 1
} else {
number = number - 1 //or number -= 1
}
can be pared down to:
var number: Int = 0
number = number + (shouldDecrease ? -1 : 1)
It’s arguable whether the more compact version is more or less understandable. Some people like the ternary operator (testCondition ? trueValue : falseValue
), some people hate it.