0
0
Swiftprogramming~20 mins

Codable protocol for encoding/decoding in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Codable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Codable encoding example?

Consider this Swift code that encodes a struct to JSON. What will be printed?

Swift
import Foundation

struct User: Codable {
    var name: String
    var age: Int
}

let user = User(name: "Alice", age: 30)
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
if let jsonData = try? encoder.encode(user), let jsonString = String(data: jsonData, encoding: .utf8) {
    print(jsonString)
}
A{"name":"Alice","age":30}
B{"age":30,"name":"Alice"}
C{"name":30,"age":"Alice"}
DRuntime error: Encoding failed
Attempts:
2 left
💡 Hint

Remember that outputFormatting = .sortedKeys sorts keys alphabetically.

Predict Output
intermediate
2:00remaining
What error does this decoding code produce?

Given this Swift code decoding JSON into a struct, what error will occur?

Swift
import Foundation

struct Product: Codable {
    var id: Int
    var name: String
}

let json = "{\"id\": \"101\", \"name\": \"Book\"}".data(using: .utf8)!

let decoder = JSONDecoder()
let product = try? decoder.decode(Product.self, from: json)
print(product != nil ? "Success" : "Failure")
ASuccess
BSyntax error
CRuntime error: type mismatch during decoding
DFailure
Attempts:
2 left
💡 Hint

Check the JSON types vs struct property types.

🧠 Conceptual
advanced
2:30remaining
Which option correctly implements custom decoding with Codable?

You want to decode a JSON where the key full_name maps to the property name in your struct. Which code snippet correctly implements this?

A
struct Person: Codable {
    var name: String
    enum CodingKeys: String, CodingKey {
        case name = "full_name"
    }
}
B
struct Person: Codable {
    var name: String
    enum CodingKeys: String, CodingKey {
        case full_name = "name"
    }
}
C
struct Person: Codable {
    var name: String
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .full_name)
    }
    enum CodingKeys: String, CodingKey {
        case full_name
    }
}
D
struct Person: Codable {
    var name: String
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
    }
    enum CodingKeys: String, CodingKey {
        case name = "full_name"
    }
}
Attempts:
2 left
💡 Hint

Look carefully at how CodingKeys maps JSON keys to struct properties.

🔧 Debug
advanced
2:00remaining
Why does this Codable struct fail to encode?

Examine this Swift struct and encoding code. Why does encoding fail?

Swift
import Foundation

struct Item: Codable {
    var id: Int
    var description: String
    var date: Date
}

let item = Item(id: 1, description: "Test", date: Date())
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
let jsonData = try? encoder.encode(item)
print(jsonData != nil ? "Encoded" : "Failed")
AEncoding succeeds and prints "Encoded"
BEncoding fails because Date is not Codable
CEncoding fails because .iso8601 strategy is not supported on JSONEncoder
DEncoding fails because description is a reserved keyword
Attempts:
2 left
💡 Hint

Check if Date supports Codable and if .iso8601 is valid.

🚀 Application
expert
2:30remaining
How many keys are in the decoded dictionary from this JSON?

Given this JSON string decoded into a Swift dictionary, how many keys does the resulting dictionary have?

Swift
import Foundation

let jsonString = "{\"a\": 1, \"b\": {\"c\": 2, \"d\": 3}, \"e\": [4,5]}"
let jsonData = jsonString.data(using: .utf8)!

let decoded = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any]
print(decoded?.count ?? 0)
A2
B5
C3
D1
Attempts:
2 left
💡 Hint

Count only the top-level keys in the dictionary.