Bird
0
0

What is wrong with this error handling code snippet?

medium📝 Debug Q7 of 15
iOS Swift - Networking
What is wrong with this error handling code snippet?
URLSession.shared.dataTask(with: url) { data, response, error in
  guard let error = error else {
    print("Error: \(error.localizedDescription)")
    return
  }
  print("Success")
}.resume()
Aerror is not optional and cannot be unwrapped
BThe guard statement logic is reversed; it should check error == nil
Cresume() is missing to start the task
Dprint statements are swapped but code runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Analyze guard statement logic

    guard let error = error unwraps error if it exists, but the code treats it as an error case incorrectly.
  2. Step 2: Correct logic for error handling

    It should check if error == nil to proceed, else handle error.
  3. Final Answer:

    The guard statement logic is reversed; it should check error == nil -> Option B
  4. Quick Check:

    Guard logic must correctly check error presence [OK]
Quick Trick: Guard should check error == nil to continue success path [OK]
Common Mistakes:
  • Reversing guard condition logic
  • Assuming error is non-optional
  • Forgetting resume() disables task

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes