[swift-evolution] ternary operator ?: suggestion

Austin Zheng austinzheng at gmail.com
Tue Jan 5 01:04:35 CST 2016


There was a popular pattern which went as follows:

let myThing = {
  if someCondition {
    return 1
  } else {
    return 2
  }
}()

It's a little ugly, but the compiler is apparently smart enough to inline/optimize away the anonymous closure. It became less popular once Swift got support for declaring lets without an initial value.

Austin

> On Jan 4, 2016, at 10:55 PM, Charles Constant via swift-evolution <swift-evolution at swift.org> wrote:
> 
> My best guesses here, since I didn't write and don't entirely agree...
> 
> > Please detail what the trade offs are
> 
> Other than more complexity, I think this refers to making the "switch" statement do two slightly different things. Of course, if we call it something else, like "match" or "which" then it stops being an issue.
> 
> > What are the other ways that Swift currently supports this?
> 
> As far as I can see, the closest we get are...
> 
>     a) The existing "switch" statement, or if else statement (preceded with a statement to declare the variable. yuck). I think this is verbose enough to qualify as "confusing"
> 
>     b) Creating an anonymous dict, and immediately accessing it (which means the keys need to be Hashable). This isn't very flexible
> 
>     c) Creating a special init or function, to map one enum, to another. This  is also verbose, and not flexible, and moves the code away from where it used (even if you never reuse the mapping).
> 
>     d) Chaining a bunch of conditions in a ternary... Horrible.
> 
> Anyone know of any better alternatives? It feels like I'm missing something.
> 

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


More information about the swift-evolution mailing list