Complete the code to declare a struct that can be encoded and decoded from JSON.
struct User: [1] {
var name: String
var age: Int
}The Codable protocol allows the struct to be encoded to and decoded from JSON easily.
Complete the code to decode JSON data into a User instance.
let decoder = JSONDecoder() let user = try decoder.[1](User.self, from: jsonData)
The decode method of JSONDecoder converts JSON data into a Swift object.
Fix the error in the decoding code by completing the blank.
do {
let user = try JSONDecoder().decode([1], from: data)
print(user.name)
} catch {
print("Failed to decode")
}The decode method requires the type itself, not an instance, so use User.self.
Fill both blanks to encode a User instance into JSON data.
let encoder = JSONEncoder() let jsonData = try encoder.[1]([2])
Use encode to convert the user instance into JSON data.
Fill all three blanks to create a dictionary from JSON data using Codable.
struct Item: Codable {
var id: Int
var name: String
}
let items = try JSONDecoder().decode([[1]].self, from: [2])
let dict = Dictionary(uniqueKeysWithValues: items.map { ($0.[3], $0.name) })Decode an array of Item from jsonData. Then map each item using its id as the key.
