The guard statement in swift

Image for post
Image for post

The guard statement has been implemented in Swift 2.0. Since then there are quite a lot rumor about its usage.

guard is not a general-purpose mechanism. This post wants to clarify some of these to help you understand WHEN and WHEN NOT to use this statement.

The basics of guard

guard condition else {
statements
}

Why using guard?

Readability of the code

if let username = usernameField.text, username != "" {  
if let email = emailField.text, email != "" {
if let password = passwordField.text, password != "" {
// do awesome stuff here
}
}
}
// error handling here ...
guard let username = usernameField.text else {  
throw SignupError.NoUsername
}
guard let email = emailField.text else {
throw SignupError.NoEmail
}
guard let password = passwordField.text else {
throw SignupError.NoPassword
}
print("username: \username, "email: \email, password: \password")

Reduce force unwraps

Common code-smells

Excessive usage of guard

Complex code in else-clause

guard let doFoo = doFooProducer.doFoo else {  
let productId = randomProducer()
if productId == 3 {
produceCar()
} else {
produceTree()
}
return
}

fin

XCode-Playground project

Written by

I’m a Software Engineer from Düsseldorf. Passionate about programming languages & technologies with vocation for agile topics.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store