[swift-evolution] ternary operator ?: suggestion

Ole Begemann ole at oleb.net
Sat Dec 5 17:12:44 CST 2015


>> This is subtle and requires thought
> 
> What do you envision as the pitfalls of the design thinking behind if/switch expressions? I’m not a compiler programmer, but a prog-lang enthusiast. I wouldn’t mind a little nudge in the right direction.

One thing that comes to mind is that if "if" is an expression, every if needs an else branch. This makes it harder to use if to conditionally perform side effects. For example, this is currently valid:

func doSomething() { ... }

if condition {
    doSomething()
}

Should this be allowed? You could argue that this should work because (a) the expression result is unused and (b) the return type of doSomething is Void, so the compiler could conceivably implicitly construct an else branch that returns (). But it would be inconsistent with other expressions. Disallowing this style could make writing typical "imperative" code harder.

– Ole


More information about the swift-evolution mailing list