Bird
0
0

Identify the error in this Swift code for making an API call: let url = URL(string: "https://api.example.com/data") let task = URLSession.shared.dataTask(with: url!) { data, response, error in print(data) } task.resume()

medium📝 Debug Q6 of 15
iOS Swift - Networking
Identify the error in this Swift code for making an API call: let url = URL(string: "https://api.example.com/data") let task = URLSession.shared.dataTask(with: url!) { data, response, error in print(data) } task.resume()
AMissing call to task.cancel() before resume()
BdataTask method is deprecated and cannot be used
CForce unwrapping URL can cause a crash if URL is nil
DThe closure does not handle the response parameter
Step-by-Step Solution
Solution:
  1. Step 1: Check URL unwrapping safety

    Force unwrapping url! is unsafe if URL(string:) returns nil.
  2. Step 2: Review other code parts

    Calling task.cancel() is not required before resume; dataTask is not deprecated; ignoring response is allowed but not best practice.
  3. Final Answer:

    Force unwrapping URL can cause a crash if URL is nil -> Option C
  4. Quick Check:

    Unsafe force unwrap = crash risk [OK]
Quick Trick: Avoid force unwrapping URLs; use safe optional binding [OK]
Common Mistakes:
  • Thinking task.cancel() is mandatory before resume()
  • Believing dataTask is deprecated
  • Ignoring response always causes errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes