What is a guard statement in Swift iOS?

1 min 6 sec read

Author: Manish Methani

Before starting this article, I strongly recommend having a look at Swift Optionals as we use them for the better understanding of guard statements in swift.

Guard in swift language executes only when the condition is false and transfer control using transfer statements like return, break, continue, or thrown. Consider this before and after scenario of guard statement,

Before using guard statement

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        var  no: Int!
        guard let number = no else {
            print("Number is nil")
            return
        }
        print("Number is  (number)")
    }
}

In this swift program, as you can see no is an integer variable which is not assigned with any value which means it contains nil value. Now what guard statement will do is it checks wether no is nil or not. If no variable is nil then else block print statement "Number is nil" is being executed and control is being returned out of function.

After using guard statement

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        var  no: Int!
        no = 4
        guard let number = no else {
            print("Number is nil")
            return
        }
        print("Number is  (number)")
    }
}

In this swift program, as you can see no is an integer variable which is assigned a value 4 in next line. Now what guard statement will do is it checks wether no is nil or not. If no variable is nil then else block has been executed. But in this program no = 4 which means no contains some value so guard statement will not be executed because variable no is not nil. And finally print statement "Number is 4" will be executed.

How was the tutorial? Nice. Right?



Deep Concept videos to crack the highly-piad interviews.

Chekout out our Youtube Channel to get detailed video content on important topics in interviews.



What is your Interview Score?

Test your skillset with the curated questions created by experts around the globe.

Book a free test slot. Now !.

It usually takes 30 mins for an online test and this test will be MCQ based. Get detailed analytics based on your test and recommedations with personalised roadmaps.

Book a test slot. Now!

Have questions about the trial coding class?

Chat with our experts to discuss

Connect on WhatsApp


Recommended tutorials

#online compiler for c     #python for programming    

#dfs and bfs algorithm     #programming with c language

#storageclass in C    #listcomprehension in python