I'm not sure whether this has been proposed, but since there's a switch extension for _ ? _ : _
floating about, I was thinking that it could be the last time for me to propose to get rid of the ternary operator
My first objection to it is that it is the only ?
in the language not associated with optionals AFAIK.
My second is that it is the only ternary operator.
My third is that it is entirely redundant with the following substitution:
infix operator ? : TernaryPrecedence
private func ? <Value>(lhs: Bool, rhs: @autoclosure () -> Value) -> Value? {
if lhs {
return rhs()
} else {
return nil
}
}
Here are some example uses:
let thisAndThat = this ? that ?? false // this ? that : false
let somethingIfThat = that ? something // that ? something : nil
let notThis = maybeThat.flatMap { $0 != this ? $0 }
As a side-point, which might not be terribly relevant, I feel that the ??
function with the non-optional rhs should probably be renamed as to be more explicit. Maybe ?:
would be appropriate here.
Compare:
let hello = this ?? that ?? else
let hello = this ?? that ?: else
In a world with the explicit ?:
operator, a human skimming the code can know, without prior information about the types of this
, that
, and else
, that the hello
is non-optional.
The reason I mention it is that, with this new operator, the diff between the old and the new lines is one character:
let thisAndThat = this ? that ?: false
let thisAndThat = this ? that : false