---
title: "Breaking labeled scopes"
slug: breaking-labeled-scopes
section: tech
date: 2017-01-30T18:01:00.000Z
canonical: https://roland.leth.ro/blog/tech/breaking-labeled-scopes
---

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

```swift
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:

```swift
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:

```swift
// 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:

```swift
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. -> We gained an indentation level.
}

// Do more stuff here.
```