forked from MadhushaPrasad/Swift-Fundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GuardStatement.swift
44 lines (33 loc) · 922 Bytes
/
GuardStatement.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import Foundation
// Guard Statement
// guard statement is used to exit out of a function if a condition is not met
// guard statement must be used inside a function
// guard statement must have an else statement
func numberLargerThanFive(number: Int) {
guard number > 5 else {
print("Number is not larger than 5")
return
}
print("Number is larger than 5")
}
func numberLargerThanFive(number: Int) {
guard number > 5, number < 10 else {
print("Number is not larger than 5")
return
} // guard statement can have multiple conditions
}
var text: String?
if let value = text {
print(value)
} else {
print("Text is nil")
}
// the above code can be written using guard statement as follows
func printText(text: String?) {
guard let value = text else {
print("Text is nil")
return
}
print(value)
}
printText(items: "Hello World")