Bird
Raised Fist0
Swiftprogramming~20 mins

Guard for early exit pattern in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Guard Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Swift code using guard?
Consider the following Swift function that uses a guard statement. What will be printed when calling checkNumber(5)?
Swift
func checkNumber(_ num: Int) {
    guard num > 10 else {
        print("Number is too small")
        return
    }
    print("Number is big enough")
}

checkNumber(5)
ANumber is big enough
BNumber is too small
CNo output
DCompilation error
Attempts:
2 left
💡 Hint
Remember guard checks a condition and exits early if false.
❓ Predict Output
intermediate
2:00remaining
What will this Swift function print when called with checkName(nil)?
Analyze the function below that uses guard to unwrap an optional String. What is the output of checkName(nil)?
Swift
func checkName(_ name: String?) {
    guard let unwrappedName = name else {
        print("No name provided")
        return
    }
    print("Hello, \(unwrappedName)!")
}

checkName(nil)
ANo name provided
BHello, !
CRuntime error
DHello, nil!
Attempts:
2 left
💡 Hint
Guard unwraps optionals safely.
🔧 Debug
advanced
2:00remaining
Why does this Swift code cause a compile error?
Examine the code below. Why does it fail to compile?
Swift
func validateAge(_ age: Int?) {
    guard age != nil else {
        print("Age is missing")
        return
    }
    print("Age is \(age!)")
}

validateAge(nil)
AMissing return statement inside guard else block
BCannot force unwrap optional age
Cguard condition must be a boolean expression
Dprint statement syntax error
Attempts:
2 left
💡 Hint
Remember guard requires exiting the current scope in else.
❓ Predict Output
advanced
2:00remaining
What is the output of this Swift function using multiple guard statements?
Look at the function below. What will it print when called with processData(5, nil)?
Swift
func processData(_ x: Int?, _ y: Int?) {
    guard let a = x else {
        print("x is nil")
        return
    }
    guard let b = y else {
        print("y is nil")
        return
    }
    print("Sum is \(a + b)")
}

processData(5, nil)
ASum is 5
Bx is nil
CNo output
Dy is nil
Attempts:
2 left
💡 Hint
Each guard checks one optional and exits early if nil.
🧠 Conceptual
expert
2:00remaining
Why is the guard statement preferred for early exit in Swift functions?
Choose the best explanation for why Swift developers use guard statements for early exit.
AGuard statements allow variables to be mutable inside the else block only.
BGuard statements automatically catch runtime errors without needing explicit error handling.
CGuard statements improve code readability by handling error cases early and reducing nested code blocks.
DGuard statements replace the need for if-else statements in all cases.
Attempts:
2 left
💡 Hint
Think about how guard affects code structure and clarity.

Practice

(1/5)
1. What is the main purpose of using guard statements in Swift?
easy
A. To define functions with multiple parameters
B. To create loops that run a fixed number of times
C. To check a condition and exit early if it is false
D. To declare constants and variables

Solution

  1. Step 1: Understand the role of guard

    guard is used to check a condition and exit the current scope early if the condition is false.
  2. Step 2: Compare with other options

    Options A, B, and C describe functions, loops, and variable declarations, which are unrelated to guard.
  3. Final Answer:

    To check a condition and exit early if it is false -> Option C
  4. Quick Check:

    Guard = early exit on false condition [OK]
Hint: Guard exits early if condition fails, keeping code clean [OK]
Common Mistakes:
  • Confusing guard with if statements
  • Thinking guard creates loops
  • Using guard to declare variables
2. Which of the following is the correct syntax for a guard statement in Swift?
easy
A. guard condition { return }
B. guard (condition) { return }
C. guard else condition { return }
D. guard condition else { return }

Solution

  1. Step 1: Recall the syntax of guard

    The correct syntax is guard condition else { ... } where the else block handles the early exit.
  2. Step 2: Check each option

    guard condition else { return } matches the correct syntax. Options A, B, and D have missing else, extra parentheses, or misplaced keywords.
  3. Final Answer:

    guard condition else { return } -> Option D
  4. Quick Check:

    Guard syntax = guard condition else { } [OK]
Hint: Remember: guard condition else { exit code } [OK]
Common Mistakes:
  • Putting condition inside parentheses incorrectly
  • Omitting else keyword
  • Placing else before condition
3. What will be the output of the following Swift code?
func checkAge(_ age: Int?) {
    guard let age = age, age >= 18 else {
        print("Access denied")
        return
    }
    print("Access granted")
}

checkAge(nil)
checkAge(16)
checkAge(21)
medium
A. Access denied Access denied Access granted
B. Access granted Access granted Access granted
C. Access denied Access granted Access denied
D. Access granted Access denied Access denied

Solution

  1. Step 1: Analyze the guard condition

    The guard checks if age is not nil and at least 18. If false, it prints "Access denied" and returns early.
  2. Step 2: Evaluate each function call

    For checkAge(nil), age is nil -> prints "Access denied".
    For checkAge(16), age is 16 < 18 -> prints "Access denied".
    For checkAge(21), age is 21 ≥ 18 -> prints "Access granted".
  3. Final Answer:

    Access denied Access denied Access granted -> Option A
  4. Quick Check:

    Guard filters nil or under 18 = Access denied [OK]
Hint: Guard lets only valid age (18+) pass, else denies [OK]
Common Mistakes:
  • Ignoring nil check in guard
  • Assuming all calls print Access granted
  • Confusing guard with if
4. Identify the error in this Swift code using guard:
func greet(name: String?) {
    guard name != nil else {
        print("No name provided")
    }
    print("Hello, \(name!)")
}
medium
A. Incorrect use of optional binding in guard
B. Missing return or exit after guard else block
C. Using force unwrap (!) inside print
D. Guard condition should be inside parentheses

Solution

  1. Step 1: Understand guard requirements

    The else block of a guard must exit the current scope (return, break, continue, or throw).
  2. Step 2: Check the code

    The else block prints a message but does not return or exit, so the function continues and force unwraps a nil value, causing a runtime error.
  3. Final Answer:

    Missing return or exit after guard else block -> Option B
  4. Quick Check:

    Guard else must exit scope [OK]
Hint: Always exit after guard else block (return, throw, etc.) [OK]
Common Mistakes:
  • Forgetting return after guard else
  • Assuming print alone exits function
  • Ignoring force unwrap risks
5. You want to write a function that takes an optional string and prints its uppercase version only if the string is non-empty. Using guard, which code snippet correctly implements this behavior?
hard
A. func printUpper(_ text: String?) { guard let text = text, !text.isEmpty else { print("Empty or nil string") return } print(text.uppercased()) }
B. func printUpper(_ text: String?) { if let text = text, !text.isEmpty { print(text.uppercased()) } else { print("Empty or nil string") } }
C. func printUpper(_ text: String?) { guard text != nil else { print("Empty or nil string") return } print(text!.uppercased()) }
D. func printUpper(_ text: String?) { guard let text = text else { print("Empty or nil string") return } if text.isEmpty { print("Empty or nil string") } print(text.uppercased()) }

Solution

  1. Step 1: Understand the requirements

    The function must print uppercase only if the string is non-nil and not empty, else print a message and exit early.
  2. Step 2: Evaluate each option

    func printUpper(_ text: String?) { guard let text = text, !text.isEmpty else { print("Empty or nil string") return } print(text.uppercased()) } uses a single guard with optional binding and emptiness check, then prints uppercase.
    func printUpper(_ text: String?) { if let text = text, !text.isEmpty { print(text.uppercased()) } else { print("Empty or nil string") } } uses if-else, not guard.
    func printUpper(_ text: String?) { guard text != nil else { print("Empty or nil string") return } print(text!.uppercased()) } only checks nil, not empty.
    func printUpper(_ text: String?) { guard let text = text else { print("Empty or nil string") return } if text.isEmpty { print("Empty or nil string") } print(text.uppercased()) } uses guard for nil, then if for empty that prints message but lacks return, so continues to print uppercased empty string, incorrect.
  3. Final Answer:

    guard let text = text, !text.isEmpty else { print("Empty or nil string"); return } print(text.uppercased()) -> Option A
  4. Quick Check:

    Guard with let and !isEmpty = correct early exit [OK]
Hint: Combine let binding and condition in one guard for clean code [OK]
Common Mistakes:
  • Checking only nil but not empty
  • Using if instead of guard for early exit
  • Splitting checks into multiple statements unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard