Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a struct that can be encoded and decoded from JSON.
iOS Swift
struct User: [1] {
var name: String
var age: Int
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Equatable instead of Codable.
Forgetting to conform to any protocol.
✗ Incorrect
The Codable protocol allows the struct to be encoded to and decoded from JSON easily.
2fill in blank
mediumComplete the code to decode JSON data into a User instance.
iOS Swift
let decoder = JSONDecoder() let user = try decoder.[1](User.self, from: jsonData)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using encode instead of decode.
Trying to use parse or serialize which are not JSONDecoder methods.
✗ Incorrect
The decode method of JSONDecoder converts JSON data into a Swift object.
3fill in blank
hardFix the error in the decoding code by completing the blank.
iOS Swift
do {
let user = try JSONDecoder().decode([1], from: data)
print(user.name)
} catch {
print("Failed to decode")
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing an instance like User() instead of the type.
Using User.Type which is a metatype but not the correct syntax here.
✗ Incorrect
The decode method requires the type itself, not an instance, so use User.self.
4fill in blank
hardFill both blanks to encode a User instance into JSON data.
iOS Swift
let encoder = JSONEncoder() let jsonData = try encoder.[1]([2])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using decode instead of encode.
Passing the type User.self instead of the instance user.
✗ Incorrect
Use encode to convert the user instance into JSON data.
5fill in blank
hardFill all three blanks to create a dictionary from JSON data using Codable.
iOS Swift
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) }) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong type in decode.
Passing wrong variable names in map closure.
✗ Incorrect
Decode an array of Item from jsonData. Then map each item using its id as the key.