Bird
0
0

Identify the error in this Swift code using guard:

medium📝 Debug Q14 of 15
Swift - Control Flow
Identify the error in this Swift code using guard:
func greet(name: String?) {
    guard name != nil else {
        print("No name provided")
    }
    print("Hello, \(name!)")
}
AIncorrect use of optional binding in guard
BMissing return or exit after guard else block
CUsing force unwrap (!) inside print
DGuard condition should be inside parentheses
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes