Bird
0
0

What will this Swift code print if the server returns JSON data successfully?

medium📝 Predict Output Q13 of 15
iOS Swift - Networking
What will this Swift code print if the server returns JSON data successfully?
let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, _, error in
  if let data = data {
    print(String(data: data, encoding: .utf8) ?? "No data")
  } else {
    print("Error")
  }
}
task.resume()
AThe JSON data as a string
BError
Cnil
DNothing prints
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the dataTask completion handler

    If data is received, it converts data to a UTF-8 string and prints it.
  2. Step 2: Understand the output when server returns JSON

    The JSON data bytes convert to a readable string and print to console.
  3. Final Answer:

    The JSON data as a string -> Option A
  4. Quick Check:

    Data received = print JSON string [OK]
Quick Trick: If data exists, it prints as string [OK]
Common Mistakes:
  • Assuming print("Error") always runs
  • Expecting nil instead of string output
  • Thinking nothing prints without resume()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes