Swift: Labeled Statement Houdinis

In Objective C, commands like break, continue, return, and goto control program flow. The following simple example calls the continue statement each time it encounters a non-zero modulus. This forces the loop to skip to the next iteration so the loop only prints out even numbers between 0 and 12.

for (int i = 0; i <= 12; i++)
{
    if (i % 2) continue;
    printf("%d\n", i);
}

Here is an adjusted Swift version of that loop. I’m not even going to pretend this version makes any sense. (If you run it, your app never terminates. The infinite do while loop continues over and over and over.) Other than the silly do-while loop, the code is more or less similar to the Objective-C example you just saw.

for i in 0...12
{
    if i % 2 != 0 {
        do {
            continue
        } while true
    }
    println(i)
}

One tiny change to this ridiculous code fixes that infinite loop. Swift allows you to add labels to for-in loops. These labels, which may look familiar to D-devs (and, I’m told, Rust), control which flow a continue statement applies to. The next examples adds a label to the for-in loop and the continue statement. Now instead of continuing the do-while loop, the statement continues the for-in loop. You get the even number output you expect.

MyForInLoop: for i in 0...12
{
    if i % 2 != 0 {
        do {
            continue MyForInLoop
        } while true
    }
    println(i)
}

In real life, you’re not going to build an infinite loop just to Houdini your way out of it. However, nested loops and switches will happen. Clarifying the level to which you want to break or  continue provides a clean sense of control over your code, as well as a welcome level of self-documentation.

Comments are closed.