Swift Tutorial · Swift Basics · Lesson 7 of 30
Swift if, guard and switch
Branch with if and switch (both usable as expressions), and exit early with guard.
if and switch expressions
Since Swift 5.9, if and switch can produce a value directly. A switch must be exhaustive and doesn't
fall through; cases can match several values, ranges, tuples and conditions with where.
func describe(_ code: Int) -> String {
switch code {
case 200, 201: "success"
case 300..<400: "redirect"
case 404: "not found"
case 500...599: "server error"
default: "other"
}
}
for code in [200, 301, 404, 503, 418] { print(code, describe(code)) }
let total = 75
let label = if total > 50 { "large order" } else { "small order" }
print(label)
let point = (3, 0)
switch point {
case (0, 0): print("origin")
case (_, 0): print("on the x axis")
case let (x, y) where x == y: print("diagonal")
default: print("elsewhere")
}
Output
200 success 301 redirect 404 not found 503 server error 418 other large order on the x axis
Run this on your computer — see “Get Started” for setup.
guard
guard condition else { return } checks a requirement and exits early when it fails, keeping the main path
unindented. Values unwrapped with guard let stay available after the guard.
func checkout(cart: [String], email: String?) -> String {
guard !cart.isEmpty else { return "cart is empty" }
guard let email, email.contains("@") else { return "need a valid email" }
return "order for \(cart.count) items, receipt to \(email)"
}
print(checkout(cart: [], email: "[email protected]"))
print(checkout(cart: ["mug"], email: nil))
print(checkout(cart: ["mug", "tea"], email: "[email protected]"))
Output
cart is empty need a valid email order for 2 items, receipt to [email protected]
Run this on your computer — see “Get Started” for setup.
Test yourself
What must a guard statement's else branch do?
Print an errorExit the current scope (return, throw, break or continue)NothingReturn a default value
Show answer
Answer: Exit the current scope (return, throw, break or continue)