Guard for early exit pattern in Swift - Time & Space Complexity
We want to see how using a guard statement to exit early affects how long the code runs.
Does this pattern change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
func findFirstPositive(_ numbers: [Int]) -> Int? {
for number in numbers {
guard number > 0 else { continue }
return number
}
return nil
}
This code looks for the first positive number in a list and stops as soon as it finds one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array elements one by one.
- How many times: Up to all elements, but usually stops early when a positive number is found.
As the list gets bigger, the code might check more numbers, but it can stop early if it finds a positive number quickly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Between 1 and 10 checks |
| 100 | Between 1 and 100 checks |
| 1000 | Between 1 and 1000 checks |
Pattern observation: The number of checks grows with input size but can stop early, so actual work varies.
Time Complexity: O(n)
This means in the worst case, the code looks at every item once, but it can finish sooner if it finds what it needs early.
[X] Wrong: "Using guard for early exit always makes the code run faster for all inputs."
[OK] Correct: Sometimes the positive number is near the end or missing, so the code still checks many items, making the time grow with input size.
Understanding how early exit patterns affect time helps you write clear and efficient code, a skill valued in many coding challenges and real projects.
"What if we changed the guard to check for a different condition that rarely happens? How would the time complexity change?"
Practice
guard statements in Swift?Solution
Step 1: Understand the role of
guardguardis used to check a condition and exit the current scope early if the condition is false.Step 2: Compare with other options
Options A, B, and C describe functions, loops, and variable declarations, which are unrelated toguard.Final Answer:
To check a condition and exit early if it is false -> Option CQuick Check:
Guard = early exit on false condition [OK]
- Confusing guard with if statements
- Thinking guard creates loops
- Using guard to declare variables
guard statement in Swift?Solution
Step 1: Recall the syntax of
The correct syntax isguardguard condition else { ... }where the else block handles the early exit.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.Final Answer:
guard condition else { return } -> Option DQuick Check:
Guard syntax = guard condition else { } [OK]
- Putting condition inside parentheses incorrectly
- Omitting else keyword
- Placing else before condition
func checkAge(_ age: Int?) {
guard let age = age, age >= 18 else {
print("Access denied")
return
}
print("Access granted")
}
checkAge(nil)
checkAge(16)
checkAge(21)Solution
Step 1: Analyze the guard condition
The guard checks ifageis not nil and at least 18. If false, it prints "Access denied" and returns early.Step 2: Evaluate each function call
ForcheckAge(nil), age is nil -> prints "Access denied".
ForcheckAge(16), age is 16 < 18 -> prints "Access denied".
ForcheckAge(21), age is 21 ≥ 18 -> prints "Access granted".Final Answer:
Access denied Access denied Access granted -> Option AQuick Check:
Guard filters nil or under 18 = Access denied [OK]
- Ignoring nil check in guard
- Assuming all calls print Access granted
- Confusing guard with if
guard:func greet(name: String?) {
guard name != nil else {
print("No name provided")
}
print("Hello, \(name!)")
}Solution
Step 1: Understand guard requirements
The else block of a guard must exit the current scope (return, break, continue, or throw).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.Final Answer:
Missing return or exit after guard else block -> Option BQuick Check:
Guard else must exit scope [OK]
- Forgetting return after guard else
- Assuming print alone exits function
- Ignoring force unwrap risks
guard, which code snippet correctly implements this behavior?Solution
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.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.Final Answer:
guard let text = text, !text.isEmpty else { print("Empty or nil string"); return } print(text.uppercased()) -> Option AQuick Check:
Guard with let and !isEmpty = correct early exit [OK]
- Checking only nil but not empty
- Using if instead of guard for early exit
- Splitting checks into multiple statements unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
