Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2 - Use case for using break on if statement?

Swift 2's guide mentions that you can end program execution of an if statement. I personally have never used break with if-statement.

A break statement ends program execution of a loop, an if statement, or a switch statement...When a break statement is followed by the name of a statement label, it ends program execution of the loop, if statement, or switch statement named by that label.

In what situation would one be using break in an if-statement? This language feature seems useless.

TEST:
if (true) {
    break TEST
}
like image 379
Boon Avatar asked Jul 18 '15 02:07

Boon


1 Answers

For example if you want to describe a number (with Strings) with reference to sets of numbers (even/rational/negative numbers) your code could look something like this:

if condition1 {
    // code
    if condition2 {
        // code
        if condition3 {
            // code
            if condition4 {
                //code
            }
        }
    }
}

You can achieve the same logic but without the nested ifs by refactoring it (using guard):

OuterIf: if condition1 {
    // code

    guard condition2 else { break OuterIf }
    // code

    guard condition3 else { break OuterIf }
    // code

    guard condition4 else { break OuterIf }
    // code
}

// reads even better when breaking out of "do"
scope: do {
    guard condition1 else { break scope }
    // code

    guard condition2 else { break scope }
    // code

    guard condition3 else { break scope }
    // code

    guard condition4 else { break scope }
    // code

}

You might think that this can also be achieved with switch and fallthrough but this doesn't work with "normal" cases because it checks all conditions and if one condition is met all following conditions aren't even evaluated.

So the fallthough has to be called conditionally.

This does work but I isn't very readable not to mention its "beauty":

let x = 4
switch x {
case _ where condition1:
    // code
    if condition2 { fallthrough }
case _ where false:
    // code
    if condition3 { fallthrough }
case _ where false:
    // code
    if condition4 { fallthrough }
case _ where false:
    // code
    break
default: break
}
like image 139
Qbyte Avatar answered Nov 22 '22 23:11

Qbyte