Bird
Raised Fist0
Swiftprogramming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of the Codable protocol in Swift?
easy
A. To create user interfaces quickly
B. To enable easy encoding and decoding of data to formats like JSON
C. To manage memory automatically
D. To handle network requests

Solution

  1. Step 1: Understand Codable's role

    The Codable protocol allows Swift types to be encoded to and decoded from external representations like JSON.
  2. Step 2: Compare with other options

    Options B, C, and D relate to UI, memory, and networking, which are unrelated to Codable.
  3. Final Answer:

    To enable easy encoding and decoding of data to formats like JSON -> Option B
  4. Quick Check:

    Codable = encoding/decoding data [OK]
Hint: Codable means convert data to/from JSON easily [OK]
Common Mistakes:
  • Confusing Codable with UI or networking protocols
  • Thinking Codable manages memory
  • Assuming Codable is for database operations
2. Which of the following is the correct way to declare a struct that supports encoding and decoding using Codable?
easy
A. struct User: Codable { var name: String; var age: Int }
B. struct User { var name: String; var age: Int }
C. struct User: Encodable { var name: String; var age: Int }
D. struct User: Decodable { var name: String; var age: Int }

Solution

  1. Step 1: Check Codable conformance

    To support both encoding and decoding, the struct must conform to Codable, which combines Encodable and Decodable.
  2. Step 2: Analyze options

    struct User: Codable { var name: String; var age: Int } correctly uses : Codable. Options C and D only support encoding or decoding, not both. struct User { var name: String; var age: Int } has no conformance.
  3. Final Answer:

    struct User: Codable { var name: String; var age: Int } -> Option A
  4. Quick Check:

    Use Codable to encode and decode both ways [OK]
Hint: Use Codable to encode and decode both ways [OK]
Common Mistakes:
  • Using only Encodable or Decodable when both needed
  • Forgetting to add Codable conformance
  • Declaring struct without protocol conformance
3. Given the following code, what will be printed?
struct Person: Codable {
    var name: String
    var age: Int
}

let jsonData = "{\"name\": \"Anna\", \"age\": 30}".data(using: .utf8)!
let decoder = JSONDecoder()
if let person = try? decoder.decode(Person.self, from: jsonData) {
    print(person.name)
} else {
    print("Failed to decode")
}
medium
A. Anna
B. Failed to decode
C. 30
D. nil

Solution

  1. Step 1: Decode JSON string to Person

    The JSON string matches the Person struct keys and types, so decoding succeeds.
  2. Step 2: Print the name property

    Since decoding succeeds, person.name is "Anna", which is printed.
  3. Final Answer:

    Anna -> Option A
  4. Quick Check:

    Decoded name = Anna [OK]
Hint: Match JSON keys exactly to struct properties [OK]
Common Mistakes:
  • Mismatching JSON keys and struct properties
  • Not unwrapping optional data safely
  • Confusing print output with age value
4. What is wrong with this code snippet that tries to decode JSON into a struct conforming to Codable?
struct Product: Codable {
    var id: Int
    var name: String
}

let json = "{\"id\": 101, \"title\": \"Book\"}"
let data = json.data(using: .utf8)!
let decoder = JSONDecoder()
let product = try? decoder.decode(Product.self, from: data)
medium
A. The JSON string is not valid JSON
B. The struct does not conform to Codable
C. The JSON key "title" does not match the struct property "name"
D. The decoder is not initialized properly

Solution

  1. Step 1: Compare JSON keys with struct properties

    The JSON has key "title" but the struct expects "name"; this mismatch causes decoding to fail.
  2. Step 2: Check other code parts

    The struct conforms to Codable, JSON is valid, and decoder is correctly initialized, so no issues there.
  3. Final Answer:

    The JSON key "title" does not match the struct property "name" -> Option C
  4. Quick Check:

    JSON keys must match struct properties exactly [OK]
Hint: JSON keys must match struct property names exactly [OK]
Common Mistakes:
  • Ignoring key name mismatches
  • Assuming decoder setup causes error
  • Not validating JSON format
5. You want to encode a struct with an optional property that should be omitted from the JSON if it is nil. Which approach using Codable is correct?
hard
A. Declare the property as optional and use JSONEncoder's default behavior
B. Use Decodable instead of Codable
C. Make the property non-optional and assign a default value
D. Use a custom encode(to:) method to skip encoding nil properties

Solution

  1. Step 1: Understand default Codable behavior

    By default, JSONEncoder encodes optional properties as null if nil, not omitting them.
  2. Step 2: Use custom encoding to omit nil

    To omit nil optional properties, implement a custom encode(to:) method and encode only non-nil values.
  3. Step 3: Evaluate other options

    Declare the property as optional and use JSONEncoder's default behavior keeps nulls, C changes property type, B is unrelated to encoding.
  4. Final Answer:

    Use a custom encode(to:) method to skip encoding nil properties -> Option D
  5. Quick Check:

    Custom encode(to:) omits nil optionals [OK]
Hint: Custom encode(to:) skips nil optionals in JSON [OK]
Common Mistakes:
  • Expecting default encoder to omit nil optionals
  • Making optional properties non-optional unnecessarily
  • Confusing Decodable with encoding behavior
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard