Complete the code to make the struct conform to Codable.
struct User: [1] {
var name: String
var age: Int
}The Codable protocol allows the struct to be encoded and decoded easily.
Complete the code to encode the user instance to JSON data.
let user = User(name: "Alice", age: 30) let encoder = JSONEncoder() let data = try? encoder.[1](user)
The encode method converts the instance into JSON data.
Fix the error in decoding JSON data to a User instance.
let decoder = JSONDecoder() let user = try? decoder.[1](User.self, from: jsonData)
The decode method is used to convert JSON data back into a Swift instance.
Fill both blanks to create a dictionary from an array of users with their names as keys.
let users = [User(name: "Bob", age: 25), User(name: "Carol", age: 28)] let userDict = Dictionary(uniqueKeysWithValues: users.map { [1] in ([1].[2], [1].age) })
We use user and name as names in the closure to map users to a dictionary with names as keys and ages as values.
Fill all three blanks to encode a User instance and convert it to a JSON string.
let user = User(name: "Dave", age: 40) let encoder = JSONEncoder() if let data = try? encoder.[1](user) { let jsonString = String(data: data, encoding: [2]) print(jsonString ?? [3]) }
We encode the user, convert data to a UTF-8 string, and print a fallback message if conversion fails.