0
0
iOS Swiftmobile~10 mins

Codable protocol for JSON parsing in iOS Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AIdentifiable
BCodable
CEquatable
DHashable
Attempts:
3 left
💡 Hint
Common Mistakes
Using Equatable instead of Codable.
Forgetting to conform to any protocol.
2fill in blank
medium

Complete 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'
Aencode
Bparse
Cdecode
Dserialize
Attempts:
3 left
💡 Hint
Common Mistakes
Using encode instead of decode.
Trying to use parse or serialize which are not JSONDecoder methods.
3fill in blank
hard

Fix 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'
AUser() -> User
BUser()
CUser.Type
DUser.self
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.
4fill in blank
hard

Fill 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'
Aencode
Buser
Cdecode
DUser.self
Attempts:
3 left
💡 Hint
Common Mistakes
Using decode instead of encode.
Passing the type User.self instead of the instance user.
5fill in blank
hard

Fill 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'
AItem
BjsonData
Cid
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong type in decode.
Passing wrong variable names in map closure.