Index
1. Swift Coding3 min 8 sec read 2. Variables in Swift
2 min 12 sec read 3. Swift Optionals
3 min 11 sec read 4. Swift Constants
2 min 19 sec read 5. Guard in Swift
1 min 6 sec read 6. Swift if, if...else Statement
2 mins 51 sec read 7. Swift Array
6 min 2 sec read 8. Swift Dictionary
3 min 16 sec read
Guard in Swift
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.
Previous Next