Swift Tips: Early Exits

Blake Merryman
BPXL Craft
Published in
2 min readAug 7, 2017

--

Early exits help reduce nesting and clearly signal what the desired and possible outcomes are. The important validation logic should be placed at the beginning of the method. This can be accomplished in a number of ways, but Swift introduced a helpful construct for dealing with early exits: guard-else.

A guard is like an inverted if-statement. If the statement evaluates to true, we carry on like normal at the same scope level. However, if the statement evaluates to false, we enter the else statement and are forced by the compiler to leave the current scope in some way (via return, continue, break, etc.). We can also handle optional binding inline using guard let.

Here’s a trivial example:

func validate(optionalParameter: MyObject) -> Bool {
if let x = optionalParameter {
if x.someBoolean {
return true
}
else {
return false
}
}
else {
return false
}
}

becomes:

func validate(optionalParameter: MyObject?) -> Bool {
guard let x = optionalParameter else { return false }
guard x.someBoolean else { return false }
return true
}

Using the guard statement will improve your code’s readability by forcing you to handle error cases right away and reducing if-statement nesting, so employ it liberally.

Join us next Monday as we explore Swift’s closure-based APIs for handling data collections.

For more insights on design and development, subscribe to BPXL Craft and follow Black Pixel on Twitter.

Black Pixel is a creative digital products agency. Learn more at blackpixel.com.

--

--