Bird
0
0

Identify the issue in this Swift function using guard:

medium📝 Debug Q7 of 15
Swift - Control Flow
Identify the issue in this Swift function using guard:
func validateInput(_ input: String?) {
    guard let text = input else {
        print("Input is nil")
    }
    print("Input: \(text)")
}
AThe optional binding syntax is incorrect; it should be 'guard input = let text'.
BThe guard's else block does not exit the function, causing a compile error.
CThe print statement inside else block is unreachable code.
DThe function should use 'if let' instead of 'guard let' here.
Step-by-Step Solution
Solution:
  1. Step 1: Understand guard requirements

    A guard statement's else block must exit the current scope (e.g., return, throw, break).
  2. Step 2: Analyze the code

    The else block prints a message but does not return or exit, so the compiler will raise an error.
  3. Step 3: Check other options

    The optional binding syntax is incorrect; it should be 'guard input = let text'. is incorrect syntax. The print statement inside else block is unreachable code. is false because the print is reachable. The function should use 'if let' instead of 'guard let' here. is a style choice, not an error.
  4. Final Answer:

    The guard's else block does not exit the function, causing a compile error. -> Option B
  5. Quick Check:

    Ensure guard else block exits scope [OK]
Quick Trick: Guard else must exit scope with return or similar [OK]
Common Mistakes:
  • Not exiting the scope in guard else block
  • Confusing optional binding syntax
  • Misunderstanding guard vs if let usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes