Skip to content
Justice Tech School

guard

guard exits early when a condition fails. Variables bound by guard stay in scope.

Example
func greet(_ name: String?) {
    guard let n = name, !n.isEmpty else { print("no name"); return }
    print("Hello \(n)")
}
greet(nil)
greet("Ada")

Exercise

Early exit.

 cond else { return }

Quiz Test

What must a guard else do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.