[swift-evolution] [Accepted with Revision] SE-0099 Restructuring Condition Clauses

Maximilian Hünenberger m.huenenberger at me.com
Thu Jun 9 07:34:55 CDT 2016


From the original thread:

> Am 01.06.2016 um 03:47 schrieb Xiaodi Wu via swift-evolution <swift-evolution at swift.org>:
> 
> <snip>
> 
> It does occur to me that there is one more option. I don't know that I like it, but it's an option no one has put forward before: recite the opening keyword when beginning a new boolean expression:
> 
> `if let x = x where x < 3 { ... }` becomes
> `if let x = x if x < 3 { ... }`
> 
> `while let item = sequence.next() where item > 0 { ... }` becomes
> `while let item = sequence.next() while item > 0 { ... }`
> 
> etc.

I've almost had the same idea... However I would not replace "where" rather than using if/while/guard as delimiters for new optional bindings/case-conditions:

// if ----------------------
if let x = y where x < 4,
if case let .some(a) = b where a > 42 {
   ...
}

// Is equivalent to:

if let x = y where x < 4 {
   if case let .some(a) = b where a > 42 {
       ...
   }
}


// guard ----------------------
guard let x = y where x < 4,
guard case let .some(a) = b where a > 42 else { ... }

// Is equivalent to:

guard let x = y where x < 4 else { ... }
guard case let .some(a) = b where a > 42 else { ... }



// while ----------------------

// "guard" or "if" should probably be used as delimiter instead of "while"
// since it is not a nested loop (imo I would go with "if"... discussable...)
while let x = y where x < 4,
while case let .some(a) = b where a > 42 {
  ...
}

// Is equivalent to:

while let x = y where x < 4 {
   guard case let .some(a) = b where a > 42 else {
       break
   }
   do { ... }
}

// or with if

while let x = y where x < 4 {
   if case let .some(a) = b where a > 42 {
       ...
   } else { break }
}



Note that all these statements have a nice symmetry to their "long form". These statements can also be similarly written without introducing a new scope and code duplication in else branches:

if ...
if ... {
   ...
} else { ... }

vs

if ... {
   if ... {
       ...
   } else { ... }
} else { ... }


Best regards
Maximilian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160609/cf443485/attachment.html>


More information about the swift-evolution mailing list