Consider this Swift code that encodes a struct to JSON. What will be printed?
import Foundation struct User: Codable { var name: String var age: Int } let user = User(name: "Alice", age: 30) let encoder = JSONEncoder() encoder.outputFormatting = .sortedKeys if let jsonData = try? encoder.encode(user), let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) }
Remember that outputFormatting = .sortedKeys sorts keys alphabetically.
The JSONEncoder with .sortedKeys outputs keys in alphabetical order, so age comes before name. The values match the struct properties.
Given this Swift code decoding JSON into a struct, what error will occur?
import Foundation struct Product: Codable { var id: Int var name: String } let json = "{\"id\": \"101\", \"name\": \"Book\"}".data(using: .utf8)! let decoder = JSONDecoder() let product = try? decoder.decode(Product.self, from: json) print(product != nil ? "Success" : "Failure")
Check the JSON types vs struct property types.
The JSON has the id as a string, but the struct expects an Int. This mismatch causes decoding to fail, so product is nil and prints "Failure".
You want to decode a JSON where the key full_name maps to the property name in your struct. Which code snippet correctly implements this?
Look carefully at how CodingKeys maps JSON keys to struct properties.
Option A correctly maps the JSON key full_name to the property name using case name = "full_name". Option A misses the mapping in CodingKeys so decoding will fail. Option A tries to decode using .name key which doesn't exist in JSON. Option A reverses the mapping incorrectly.
Examine this Swift struct and encoding code. Why does encoding fail?
import Foundation struct Item: Codable { var id: Int var description: String var date: Date } let item = Item(id: 1, description: "Test", date: Date()) let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 let jsonData = try? encoder.encode(item) print(jsonData != nil ? "Encoded" : "Failed")
Check if Date supports Codable and if .iso8601 is valid.
Date conforms to Codable and JSONEncoder supports .iso8601 dateEncodingStrategy. The property name description is allowed. So encoding succeeds.
Given this JSON string decoded into a Swift dictionary, how many keys does the resulting dictionary have?
import Foundation let jsonString = "{\"a\": 1, \"b\": {\"c\": 2, \"d\": 3}, \"e\": [4,5]}" let jsonData = jsonString.data(using: .utf8)! let decoded = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] print(decoded?.count ?? 0)
Count only the top-level keys in the dictionary.
The JSON has three top-level keys: a, b, and e. Nested keys inside b are not counted at this level.