Bird
0
0

Consider the following Swift code snippet:

medium📝 Predict Output Q4 of 15
iOS Swift - Networking
Consider the following Swift code snippet:
let url = URL(string: "https://example.com/image.jpg")!
URLSession.shared.dataTask(with: url) { data, response, error in
  if let data = data, let image = UIImage(data: data) {
    print("Image loaded successfully")
  } else {
    print("Failed to load image")
  }
}.resume()
What will be printed if the image data is corrupted and cannot be converted to a UIImage?
AThe app will crash
B"Image loaded successfully"
CNothing will be printed
D"Failed to load image"
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the data and image conversion

    If data is non-nil but corrupted, UIImage(data: data) returns nil.
  2. Step 2: Check the if-let condition

    The condition if let data = data, let image = UIImage(data: data) fails because image is nil.
  3. Step 3: Execute the else block

    Therefore, the else block executes, printing "Failed to load image".
  4. Final Answer:

    "Failed to load image" -> Option D
  5. Quick Check:

    Remember that UIImage(data:) returns nil for invalid data [OK]
Quick Trick: UIImage(data:) returns nil if data is invalid [OK]
Common Mistakes:
  • Assuming image is always created if data exists
  • Not handling the else case for failed image creation
  • Expecting a crash instead of safe nil handling

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes