0
0
Swiftprogramming~10 mins

Codable protocol for encoding/decoding in 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 make the struct conform to Codable.

Swift
struct User: [1] {
    var name: String
    var age: Int
}
Drag options to blanks, or click blank then click option'
ACodable
BEquatable
CHashable
DIdentifiable
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 encode the user instance to JSON data.

Swift
let user = User(name: "Alice", age: 30)
let encoder = JSONEncoder()
let data = try? encoder.[1](user)
Drag options to blanks, or click blank then click option'
Aencode
Bserialize
Cdecode
Dconvert
Attempts:
3 left
💡 Hint
Common Mistakes
Using decode instead of encode.
Trying to use serialize or convert which are not methods of JSONEncoder.
3fill in blank
hard

Fix the error in decoding JSON data to a User instance.

Swift
let decoder = JSONDecoder()
let user = try? decoder.[1](User.self, from: jsonData)
Drag options to blanks, or click blank then click option'
Aencode
Bserialize
Cdecode
Dconvert
Attempts:
3 left
💡 Hint
Common Mistakes
Using encode instead of decode.
Trying to use serialize or convert which are not methods of JSONDecoder.
4fill in blank
hard

Fill both blanks to create a dictionary from an array of users with their names as keys.

Swift
let users = [User(name: "Bob", age: 25), User(name: "Carol", age: 28)]
let userDict = Dictionary(uniqueKeysWithValues: users.map { [1] in ([1].[2], [1].age) })
Drag options to blanks, or click blank then click option'
Auser
Bname
Cage
Ditem
Attempts:
3 left
💡 Hint
Common Mistakes
Using property names instead of variable names in the closure parameters.
Mixing up the order of variables.
5fill in blank
hard

Fill all three blanks to encode a User instance and convert it to a JSON string.

Swift
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])
}
Drag options to blanks, or click blank then click option'
Aencode
Butf8
C"Invalid JSON"
Ddecode
Attempts:
3 left
💡 Hint
Common Mistakes
Using decode instead of encode.
Using wrong encoding like ascii.
Not providing a fallback string.