Pitch: Multi-statement if/switch/do expressions

I'm excited for this feature. It's a better alternative to the { closure hacks }() that we have to do now.

I will say it feels unnatural that a then statement only applies to the innermost if, switch, or do, because it's dissimilar to return and break in typical patterns of Swift code, like returning in one branch of an if but not another, or making an early return within a guard statement.

How about making a then statement apply to the innermost if, switch, or do that isn't in statement position? Or in other words, the innermost if, switch, or do that's assigned to a variable or used within another expression. That should rule out the common control flow patterns, since it's currently impossible to use control flow within an expression; while still preventing "unused result" bugs involving statement-level if, switch, and do blocks. So for example:

let x = if .random() {
  print("hello")
  if .random() {
    then 1 // this `then` applies to the outer `if` because
           // the inner `if` isn't assigned to anything or
           // used within another expression
  } else {
    then 2
  }
} else {
  3
}
5 Likes