ProgramGuru

Exit early with guard

Exit early with guard

A function that cannot form a valid report should stop before using missing information. Guard states a condition required for the work that follows. If the condition fails, its else block must leave the enclosing scope, commonly with return or throw.

Guard can unwrap an optional and keep its bound value available in the remainder of the scope. This differs from if-let binding, whose value is confined to its successful branch. Early exits can keep the main success path readable instead of nesting every later operation.

What you’ll learn

  • Use guard binding to keep the successful value in scope.
  • Choose an appropriate early exit for a failed precondition.

Exit early with guard in the example

  1. Missing score

    A function that cannot form a valid report should stop before using missing information.

    Missing score
  2. Early return

    Guard can unwrap an optional and keep its bound value available in the remainder of the scope.

    Early return
  3. Present score continues

    The first call prints the absence message and returns before the final print.

    Present score continues
The first call prints the absence message and returns before the final print. The second binds actual to 80, passes the guard and prints the score. The underscore removes the external argument label; the next function lessons explain labels in detail.

Work through exit early with guard

Save this complete program as main.swift and run it with the Swift toolchain. No separate input file is needed.

Swift · complete program

func showScore(_ score: Int?) {
  guard let actual = score else {
    print("Awaiting result")
    return
  }
  print("Score:", actual)
}
showScore(nil)
showScore(80)

Expected output

Awaiting result
Score: 80

Follow the execution

The first call prints the absence message and returns before the final print. The second binds actual to 80, passes the guard and prints the score. The underscore removes the external argument label; the next function lessons explain labels in detail.

Try this program in the Swift compiler. Paste the complete source above.

Practice: Exit early with guard

Your task: Could you remove return from the guard failure branch?

Swift · complete program

func showScore(_ score: Int?) {
  guard let actual = score else {
    print("Awaiting result")
    return
  }
  print("Score:", actual)
}
showScore(nil)
showScore(80)

Worked answer

No, not while leaving that branch without another scope-exiting operation. Guard requires its failed branch to exit so the later code can rely on the condition and bound value.

Exit the required scope

Use a guard for an actual precondition, not to disguise every normal alternative. In loops, continue or break can satisfy the required exit from the appropriate scope. A successful presence check still may need separate range validation.

Check your decision

Could you remove return from the guard failure branch?
Choose one answer. You can try again.

Answer and explanation

No, not while leaving that branch without another scope-exiting operation.

No, not while leaving that branch without another scope-exiting operation. Guard requires its failed branch to exit so the later code can rely on the condition and bound value.

Exit early with guard in practice

No, not while leaving that branch without another scope-exiting operation. Guard requires its failed branch to exit so the later code can rely on the condition and bound value. Use a guard for an actual precondition, not to disguise every normal alternative.

Further reading: official Swift language guide.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Arrays: keep an ordered list →