How to use guard in Swift to make your code more readable

The cleaner your code is, the easier it is to maintain

Gurjit Singh
Mac O’Clock
Published in
2 min readApr 10, 2021

--

Photo by Clément Hélardot on Unsplash

When your project becomes more complex, you’ll need to write more stable and simple code. Every line of code you write is important because the cleaner your code is, the easier it is to maintain.

We’ll use the guard statement to help handle control flow in this post. The provided condition in the guard statement must be valid in order for the code to be executed after the guard statement. If the given condition is false, the guard statement’s else block will be executed.

Basic Expression

guard condition else {
//execute some code when statement is false
}
//execute some code when statement is true

Comparison of guard statement with if statement

Return in the else block is needed for the guard statement to leave the current scope. The if statement, on the other hand, does not require a return to exit the current scope. To say the comparison of both, we are writing the same function with if and guard.

func checkEvenNumber(number: Int) {
if number % 2 == 0 {
print("Number" is even)
}
}

Using guard statement,

func checkEvenNumber(number: Int) {
guard number % 2 != 0 {
return
}
print("Number" is even)
}

Early exit using return

You can write function that return early if the specified condition is not met using this style. By removing all unnecessary conditions and using return, we can make our code cleaner and more readable, which is not possible with an if statement.

Using guard with optional

To work with optional, we’ll use guard-let instead of if-let.

guard let tyres == 2 else { return }
// vehicle is two wheeler
print("This vehicle has \(tyres.count) tyres")

To unwrap optionals in a single sentence, you can use both if let and guard let. However, guard let allows us to access all values through the rest of the function, which we can’t do with if let.

Conclusion

The use of a guard statement makes code more readable and maintainable. However, we must not overlook the use of the if statement. When it’s necessary, you can use an if sentence.

To find newest tips and tricks about iOS development, Xcode and Swift please visit https://www.gurjit.co

Thanks!

--

--

Gurjit Singh
Mac O’Clock

I’m Computer Science graduate and an iOS Engineer who writes about Swift and iOS development. Follow me on twitter @gurjitpt and for more articles www.gurjit.co