[swift-evolution] ternary operator ?: suggestion

Paul Ossenbruggen possen at gmail.com
Sat Jan 16 13:04:57 CST 2016


Once again I really like the proposal, I am rereading it after a busy week of work, one thing that gets me excited is that it makes it so the ternary syntax is no longer necessary (we can leave it for historical reasons, but I don’t see it as necessary). The question mark syntax is really saying “map” this boolean value to these other values:

let result = niceDay.map { cases true: “Sunny”, false: “Cloudy” }

compared to ternary:

let result = niceDay ? “Sunny” : “Cloudy”

the former reads better and I think it helps make the purpose of “map" even more obvious to everyone, in other words it solves the problem of the ternary being weird magic. One thing that this lacks versus ternary is that is is not as concise. I really want to say something like this if we could add the index approach, wondering if it would make sense to add one more form so it could really be a replacement for ternary (still not saying we would remove it from the language): 

let result = niceDay.map { “Sunny” : “Cloudy” }

which would almost be as compact. So the : is the default case. We could also support an indexed list:

let dayOfWeek = 4
let result = dayOfWeek.map { “Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” : ”Day out of range." }

So this would introduce a third kind of syntax for a block. However, this may be better than an array lookup because it deals with a value that is out of range:  

// array index lookup, fails
let dayOfWeek = 8
let result = dayOfWeek[“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” ]

I am not saying any of this has to be part of the proposal, just exploring some more ideas and focusing on how to remain concise, yet clear.

This goes even further but would not be part of this proposal, array could be enhanced to support a out of range value. 

let col = [“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” : “Out of range.”]
col[8] 

How often you you  have an array that you don’t want to deal with out of range values. Looks like a separate proposal. 

- Paul

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160116/a42256a5/attachment.html>


More information about the swift-evolution mailing list