Fill the blank
Fill the blank to send newUser (an Encodable struct) as JSON.
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = ____
let (data, response) = try await URLSession.shared.data(for: request)Hint 1 of 1
Which API works with Encodable?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A try JSONEncoder().encode(newUser)
Correct. It turns the Encodable value into JSON Data.
Why not the others?
- B
newUser as Data. A struct can't be cast to Data. - C
try JSONSerialization.data(withJSONObject: newUser). JSONSerialization only accepts Foundation types, so a custom struct crashes. - D
String(describing: newUser).data(using: .utf8). That is a debug description, not JSON.