[swift-evolution] [swift-evolution-announce] [Review] SE-0099: Restructuring Condition Clauses

Maximilian H├╝nenberger m.huenenberger at me.com
Tue Jun 7 15:41:17 CDT 2016


> 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 (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


More information about the swift-evolution mailing list