Bird
0
0

Given this code snippet, what will happen if the network call fails?

medium📝 Predict Output Q5 of 15
iOS Swift - Networking
Given this code snippet, what will happen if the network call fails?
func fetchData() {
  URLSession.shared.dataTask(with: url) { data, response, error in
    guard error == nil else {
      print("Failed with error")
      return
    }
    print("Data received")
  }.resume()
}
ACrashes because error is not unwrapped
BPrints "Data received" even if error exists
CDoes nothing because resume() is missing
DPrints "Failed with error" and returns early
Step-by-Step Solution
Solution:
  1. Step 1: Understand guard statement usage

    The guard checks if error is nil; if not, it prints failure and returns early.
  2. Step 2: Confirm resume() call

    resume() is called, so the task runs and closure executes.
  3. Final Answer:

    Prints "Failed with error" and returns early -> Option D
  4. Quick Check:

    Guard error check returns on error = Prints "Failed with error" and returns early [OK]
Quick Trick: guard error == nil else returns early on failure [OK]
Common Mistakes:
  • Assuming data received prints despite error
  • Thinking error must be unwrapped forcibly
  • Forgetting resume() disables task

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes