[swift-evolution] Control Flow Expressions

Chris Lattner clattner at apple.com
Sat Dec 5 12:15:49 CST 2015


> On Dec 4, 2015, at 3:05 AM, Sergey Shulepov <s.pepyakin at gmail.com> wrote:
> 
> Hello. 
> 
> It would be cool if control flow statements like "switch", "if" can be used as expressions, such as in languages like Scala, Rust and Kotlin,
> so instead of writing:
> 
> var message: String
> if x % 2 == 0 {
> message = "x is even"
> } else {
> message = "x is odd"
> }
> 
> you can write:
> 
> let message: String = if x % 2 == 0 { "x is even" } else { "x is odd" }
> 
> I'm not into any kind of compiler development, and don't know is it feasible to introduce such change at the moment, but at least, I would like to hear why not.

FWIW, I (and many other people) would like to consider turning many statement-y things in swift into expressions.  I’d love to see the weird ?: ternary operator get nuked and replaced with an if/else expression of some sort.  This is an area that the apple team hasn’t had bandwidth to consider carefully.

That said, there are challenges here in the details.  How will the grammar work? Exactly which statements should be included (certainly if and switch, any others)?

Further, it is important to consider whether the code written using this will actually be *better* than the code written with these things as statements.  For example, the “switch” blocks tend to be very large, and turning them into expressions encourages additional indentation.  Swift already allows ‘let’ values to be initialized on multiple paths, so is the win actually that great?

Given that statements-as-expressions would provide another way to do things (they are a purely syntax extension) the barrier should high to add them.  They will add complexity and surface area to the language, so they need to pay that complexity.

-Chris



More information about the swift-evolution mailing list