Bird
0
0

Identify the issue in the following Swift code snippet for loading an image from a URL:

medium📝 Debug Q6 of 15
iOS Swift - Networking
Identify the issue in the following Swift code snippet for loading an image from a URL:
let url = URL(string: "https://example.com/image.png")
URLSession.shared.dataTask(with: url!) { data, response, error in
  let image = UIImage(data: data!)
  imageView.image = image
}.resume()
AForce unwrapping <code>data</code> without checking for nil can cause a crash
BThe URL is not force unwrapped, so it will not compile
CThe image is set on the main thread correctly
DThe dataTask is missing the resume() call
Step-by-Step Solution
Solution:
  1. Step 1: Check force unwrapping of data

    Using data! without verifying if data is nil can cause runtime crashes.
  2. Step 2: Consider thread safety

    Updating imageView.image must be done on the main thread, but this code updates it directly inside the background thread.
  3. Step 3: Evaluate other options

    URL is force unwrapped correctly with url!, and resume() is called.
  4. Final Answer:

    Force unwrapping data without nil check can cause a crash -> Option A
  5. Quick Check:

    Always safely unwrap optionals and update UI on main thread [OK]
Quick Trick: Never force unwrap data without nil check [OK]
Common Mistakes:
  • Force unwrapping optionals without validation
  • Updating UI on background threads
  • Ignoring error handling in network calls

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes