Which Swift code snippet correctly creates the JSON body for this conditional inclusion?
hard📝 Application Q15 of 15
iOS Swift - Networking
You want to send a POST request with a JSON body containing user info, but only include the "email" field if it is not empty. Which Swift code snippet correctly creates the JSON body for this conditional inclusion?
var jsonBody = ["name": "Bob"]
if !email.isEmpty {
jsonBody["email"] = email
}
request.httpBody = try? JSONSerialization.data(withJSONObject: jsonBody) creates a mutable dictionary and adds "email" only if not empty, which is correct.
Step 2: Check other options for errors
let jsonBody = ["name": "Bob", "email": email.isEmpty ? nil : email]
request.httpBody = try? JSONSerialization.data(withJSONObject: jsonBody) uses nil in dictionary literal which is invalid; var jsonBody = ["name": "Bob", "email": email]
if !email.isEmpty {
jsonBody.removeValue(forKey: "email")
}
request.httpBody = try? JSONSerialization.data(withJSONObject: jsonBody) uses inverted condition, removing email when it is not empty, incorrect; let jsonBody = ["name": "Bob"]
if email != "" {
jsonBody["email"] = email
}
request.httpBody = try? JSONSerialization.data(withJSONObject: jsonBody) tries to mutate immutable dictionary.
Final Answer:
var jsonBody = ["name": "Bob"]\nif !email.isEmpty {\n jsonBody["email"] = email\n}\nrequest.httpBody = try? JSONSerialization.data(withJSONObject: jsonBody) -> Option D
Quick Check:
Mutable dict + conditional add = C [OK]
Quick Trick:Use var dictionary and add keys conditionally [OK]
Common Mistakes:
Using let dictionary and trying to mutate it
Including nil values in dictionary literal
Adding then removing keys instead of conditional add
Master "Networking" in iOS Swift
9 interactive learning modes - each teaches the same concept differently