[swift-evolution] [Pitch] Use "where" in combination with "??" to provide Ternary-like functionality

Charles Constant charles at charlesism.com
Mon May 23 03:29:59 CDT 2016


Here's a few examples of what this change would allow.

I just plucked the first instances of other people's switch statements that
I found on GitHub.

If there were an easy way to search GitHub for chained ternary expressions,
I would have added some examples of those too, since they could all be
improved with this where clause + ??.


mutating func toggle() {

switch self{

case Off:

self = On

case On:

self = Off

}

}




mutating func toggle() {

self = .On where (self == .Off) ?? .Off

}




switch switchNumberThree {

case 10, 11, 12:

println("It is \(switchNumberThree)")

default:

("It is none of them!")

}



println(

"It is \(switchNumberThree)" where 10...12 ~= switchNumberThree

?? "It is none of them!"

)




switch x {

case 1:

j++

case 2:

j++

case 3:

j++

case 4:

j++

fallthrough

case 5:

j++

fallthrough

default:

j++

}



j = j+1 where (4...5 ~= x) ?? j+2
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160523/f1e8201c/attachment.html>


More information about the swift-evolution mailing list