Bird
0
0

This Swift code attempts to handle a network error but has a logic error:

medium📝 Debug Q14 of 15
iOS Swift - Networking
This Swift code attempts to handle a network error but has a logic error:
URLSession.shared.dataTask(with: url) { data, response, error in
  if error == nil {
    print("No error")
  } else {
    print(error!.localizedDescription)
  }
}.resume()
What is the likely cause of the logic error?
ANot calling resume() on the data task
BForce unwrapping error when it is nil
CUsing error == nil instead of error != nil
DPrinting error.localizedDescription without checking error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the logic and best practice

    The code checks if error == nil for success first, then handles error in else (safe unwrap). While functional, best practice is to check if error != nil first to explicitly handle failures before success.
  2. Final Answer:

    Using error == nil instead of error != nil -> Option C
  3. Quick Check:

    Error check logic reversed [OK]
Quick Trick: Check error != nil to handle errors safely [OK]
Common Mistakes:
  • Reversing error check logic
  • Force unwrapping error without check
  • Not calling resume() on data task

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes