iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

if / guard / switch

Swift has if, guard, switch with pattern matching, plus the modern if let / guard let unwrapping. switch is exhaustive and compiler-checked.

Patterns, guard, switch

EXAMPLE
let age = 36

// 1) Classic if / guard
if age >= 18 {
    print("adult")
} else if age >= 13 {
    print("teen")
} else {
    print("kid")
}

// 2) guard — early return, flat happy path
func greet(_ name: String?) {
    guard let name, !name.isEmpty else {
        print("no name")
        return
    }
    print("hi, \(name)")
}

// 3) switch — exhaustive, value bindings, where clauses
let score = 78
switch score {
case 0:                print("zero")
case 1...59:           print("fail")
case 60...79:          print("pass")
case let s where s > 100: print("out of range")
case 80...:             print("distinction")
default:                print("impossible")
}

// 4) Switch on a tuple
let point = (1, -1)
switch point {
case (0, 0):                  print("origin")
case (_, 0):                  print("on x axis")
case (0, _):                  print("on y axis")
case (let x, let y) where x == y: print("diagonal")
default:                        print("general")
}

// 5) Switch on an enum with associated values
enum Event {
    case tap(at: Date)
    case scroll(dy: Double)
    case error(Error)
}

func handle(_ e: Event) {
    switch e {
    case .tap(let at):              print("tap @ \(at)")
    case .scroll(let dy) where abs(dy) > 200: print("fast scroll")
    case .scroll(let dy):           print("scroll \(dy)")
    case .error(let err):           print("err \(err)")
    }
}

Why it matters

Switch on enums is the Swift way to model state machines. Each transition becomes a case the compiler nags you about until exhaustive — impossible states become impossible.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
let n = 7
if n > 10 { print("big") }
else if n > 0 { print("small") }
else { print("non-positive") }

guard n > 0 else { return }

switch n {
case 0: print("zero")
case 1...9: print("digit")
default: print("big")
}
Try it Yourself »

Discussion

Loading…