Breaking labeled scopes

:  ~ 2 min read

break is used to exit the current scope, for example a for loop:

for i in 1...10 {
    guard i < 9 else { break }
    // Code here.
}

But what if we have nested loops, and we want to break a specific one? Swift has us covered, with labels:

outer: for i in 1...10 {
    inner: for j in 1...10 {
        guard i < 9 else { break outer }
        guard j < 8 else { break inner }
        // Code here.
    }
}

But today I found something interesting; you can label if blocks, as well:

// Works with non optional binding ifs as well.
abCheck: if let a = b() {
    guard a.condition else { break abCheck }
    // Code here.
}

This won't be that useful, or used that often, but it's going to be a relief for cases like:

if let a = b() {
    // Do something here. -> This doesn't let us combine the two ifs into one statement.

    if let c = a.d() {
        // Do something else here.
    }
}

// Do more stuff here. -> This doesn't let us use a guard above.

->

abCheck: if let a = b() {
    // Do something here.

    guard let c = a.d() else { break abCheck }

    // Do something else here.
}

// Do more stuff here.