Swift Tips: Early Exits

Blake Merryman
Aug 7, 2017 · 2 min read

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.

BPXL Craft

Design and technology articles from the Black Pixel team. blackpixel.com

Blake Merryman

Written by

 Software Engineer

BPXL Craft

Design and technology articles from the Black Pixel team. blackpixel.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade