How to use guard in Swift to write code more readable

Swift Guard Control flow

Posted on 29 Mar 2021 . 2min read


It's necessary to write more robust and simple code as long as your project goes more complex. Every line of code you are writing is matters because the more your code cleaner the more easier is to maintain.


In this article, we will use guard statement to better manage control flow. In guard statement, the given condition must be true to execute the code after the guard statement. If given condition is false then else block of guard statement will execute.


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

The guard statement must exit the current scope using return in else block. On the other hand, the if statement doesn't need to write return to exit the current scope. We are writing same function with if and guard to say the comparison of both.

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


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


Early exit using return

With this style you can write function will returns early if given condition is not met. By eliminating all unwanted conditions and using return will cleaner our code and readability which is not possible with if statement.


Using guard with optionals

We will use guard-let instead of if let to work with optional.

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

You can use both if let and guard let to unwrap optionals in one statement. But guard let provides ability to available all values through the rest of function which we can't achieve with if let.


Conclusion

Guard statement helps code to written more clearer and easier to maintain. But we can't neglect the use of if statement to. You can use if statement when it is appropriate.


Don’t hesitate to contact me if you have any questions or queries. Follow me on twitter @gurjitpt for any updates.

Thanks!


Share this article



Written By

Generic placeholder image

Gurjit Singh

I’m Computer Science graduate and an iOS Engineer who writes about Swift and iOS development. Follow me for more updates:


Discover articles by topics

SwiftUI Class Struct Networking XCode NSCache Enum Optionals Property Observers Closures Guard Reviews StoreKit App Store Algorithms Testing Operators Protocol Extensions Weak Unowned SwiftData WWDC23 GCD API Admob SwiftLint Lottie Foreach Objective-C UIKit NavigationSplitView

Related Articles


Connection failed: Access denied for user 'techwyhu'@'server82.web-hosting.com' (using password: YES)