Bird
Raised Fist0
iOS Swiftmobile~20 mins

Codable protocol for JSON parsing in iOS Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Codable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
📝 Syntax
intermediate
2:00remaining
Correct Codable struct syntax
Which option correctly defines a Swift struct that conforms to Codable for parsing JSON with keys name (String) and age (Int)?
A
class Person: Codable {
  var name: String
  var age: Int
}
B
struct Person {
  var name: String
  var age: Int
  func encode() {}
}
C
}
tnI :ega rav  
gnirtS :eman rav  
{ elbadoC :nosreP tcurts
D
struct Person: Codable {
  var name: String
  var age: Int
}
Attempts:
2 left
💡 Hint
Remember, Codable works with structs and classes, but types must match JSON keys exactly.
❓ ui_behavior
intermediate
2:00remaining
Decoding JSON with Codable
Given this JSON string: {"name":"Alice","age":30}, which option correctly decodes it into a Person struct using JSONDecoder?
iOS Swift
struct Person: Codable {
  var name: String
  var age: Int
}

let jsonString = "{\"name\":\"Alice\",\"age\":30}"
A
let data = jsonString.data(using: .utf8)!
let person = try JSONDecoder().decode(Person.self, from: data)
Blet person = try JSONDecoder().decode(Person.self, from: jsonString)
C
let data = jsonString.data(using: .ascii)!
let person = try JSONDecoder().decode(Person.self, from: data)
D
let data = jsonString.data(using: .utf8)!
let person = JSONDecoder().decode(Person.self, from: data)
Attempts:
2 left
💡 Hint
You must convert the JSON string to Data using UTF-8 encoding before decoding.
❓ lifecycle
advanced
2:00remaining
Handling missing JSON keys during decoding
If a JSON response sometimes omits the age key, how should you define the Person struct to decode successfully without errors?
A
struct Person: Codable {
  var name: String
  var age: Int = 0
}
B
struct Person: Codable {
  var name: String
  var age: String?
}
C
struct Person: Codable {
  var name: String
  var age: Int?
}
D
struct Person: Codable {
  var name: String
  var age: Int
}
Attempts:
2 left
💡 Hint
Make the property optional to handle missing keys gracefully.
❓ navigation
advanced
2:00remaining
Custom key mapping with Codable
Given JSON {"full_name":"Bob Smith","age":25}, how do you map full_name to a Swift property name in a Codable struct?
A
struct Person: Codable {
  var full_name: String
  var age: Int
}
B
struct Person: Codable {
  var name: String
  var age: Int
  enum CodingKeys: String, CodingKey {
    case name = "full_name"
    case age
  }
}
C
struct Person: Codable {
  var name: String
  var age: Int
  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    name = try container.decode(String.self, forKey: .full_name)
    age = try container.decode(Int.self, forKey: .age)
  }
  enum CodingKeys: String, CodingKey {
    case full_name
    case age
  }
}
D
struct Person: Codable {
  var name: String
  var age: Int
  enum CodingKeys: String, CodingKey {
    case name
    case age
  }
}
Attempts:
2 left
💡 Hint
Use CodingKeys enum to map JSON keys to different property names.
🔧 Debug
expert
2:00remaining
Identify decoding error cause
This code throws a decoding error. What is the cause? struct Person: Codable { var name: String var age: Int } let json = "{\"name\":\"Eve\"}" // age key missing let data = json.data(using: .utf8)! let person = try JSONDecoder().decode(Person.self, from: data)
iOS Swift
struct Person: Codable {
  var name: String
  var age: Int
}

let json = "{\"name\":\"Eve\"}"
let data = json.data(using: .utf8)!
let person = try JSONDecoder().decode(Person.self, from: data)
AThe JSON is missing the required 'age' key, causing a decoding failure.
BThe JSON string is not valid UTF-8 encoded data.
CThe 'name' property is not optional but missing in JSON.
DThe struct must be a class to decode properly.
Attempts:
2 left
💡 Hint
Check if all non-optional properties have matching keys in JSON.

Practice

(1/5)
1. What does the Codable protocol in Swift help you do?
easy
A. Convert Swift objects to and from JSON easily
B. Create user interface elements
C. Manage app navigation
D. Handle network connections

Solution

  1. Step 1: Understand the purpose of Codable

    The Codable protocol is designed to simplify converting data between Swift objects and external formats like JSON.
  2. Step 2: Identify the correct use case

    It is not related to UI, navigation, or networking directly, but specifically for encoding and decoding data.
  3. Final Answer:

    Convert Swift objects to and from JSON easily -> Option A
  4. Quick Check:

    Codable = Convert JSON [OK]
Hint: Codable means easy JSON conversion [OK]
Common Mistakes:
  • Confusing Codable with UI or navigation tasks
  • Thinking Codable manages network calls
  • Assuming Codable is for database storage
2. Which of the following is the correct way to declare a Swift struct that can be encoded and decoded using Codable?
easy
A. struct User { var name: String }
B. struct User: Decodable { var name: String }
C. class User: Codable { var name: String }
D. struct User: Codable { var name: String }

Solution

  1. Step 1: Check the struct declaration

    To use Codable, the struct must conform to the Codable protocol explicitly.
  2. Step 2: Verify the syntax

    struct User: Codable { var name: String } correctly declares a struct conforming to Codable. struct User { var name: String } lacks Codable conformance. class User: Codable { var name: String } uses a class, which is valid but not asked here. struct User: Decodable { var name: String } only conforms to Decodable, missing Encodable.
  3. Final Answer:

    struct User: Codable { var name: String } -> Option D
  4. Quick Check:

    Struct + Codable = struct User: Codable { var name: String } [OK]
Hint: Use struct with Codable for JSON parsing [OK]
Common Mistakes:
  • Forgetting to add Codable conformance
  • Using class instead of struct when asked
  • Using only Decodable without Encodable
3. Given this JSON string:
{"id": 10, "title": "Book"}

And this Swift struct:
struct Item: Codable { var id: Int; var title: String }

What will be the value of item.title after decoding?
medium
A. "id"
B. "Book"
C. 10
D. nil

Solution

  1. Step 1: Match JSON keys to struct properties

    The JSON has keys "id" and "title" matching the struct's properties.
  2. Step 2: Decode JSON to struct

    Decoding will assign the value "Book" to title and 10 to id.
  3. Final Answer:

    "Book" -> Option B
  4. Quick Check:

    Decoded title = "Book" [OK]
Hint: JSON keys match struct properties exactly [OK]
Common Mistakes:
  • Confusing property names with values
  • Expecting numeric value for title
  • Assuming decoding fails and returns nil
4. What is wrong with this Swift code for decoding JSON?
let json = "{\"name\": \"Alice\"}".data(using: .utf8)!
struct Person: Codable { var name: String }
let person = try JSONDecoder().decode(Person.self, from: json)
medium
A. The JSONDecoder call is missing try/catch
B. The struct does not conform to Codable
C. The JSON string is not valid
D. The JSON data is nil

Solution

  1. Step 1: Check JSON string validity

    The JSON string is valid and properly escaped.
  2. Step 2: Verify Codable conformance

    The struct Person conforms to Codable correctly.
  3. Step 3: Analyze JSONDecoder usage

    The decode call uses try but lacks a do-catch block or try? to handle errors, which is required.
  4. Final Answer:

    The JSONDecoder call is missing try/catch -> Option A
  5. Quick Check:

    Missing error handling for try [OK]
Hint: Always handle errors with try when decoding JSON [OK]
Common Mistakes:
  • Ignoring error handling with try
  • Assuming JSON string is invalid
  • Forgetting Codable conformance
5. You have this JSON:
{"user": {"id": 1, "name": "Bob"}}

And these Swift structs:
struct User: Codable { var id: Int; var name: String }
struct Response: Codable { var user: User }

How do you decode the JSON into a Response object?
hard
A. Use JSONSerialization.jsonObject(with: jsonData)
B. Use JSONDecoder().decode(User.self, from: jsonData)
C. Use JSONDecoder().decode(Response.self, from: jsonData)
D. Use JSONEncoder().encode(Response.self, from: jsonData)

Solution

  1. Step 1: Identify the top-level JSON structure

    The JSON has a top-level key "user" matching the Response struct's property.
  2. Step 2: Choose correct decoding target

    To decode the entire JSON, decode to Response.self, which contains User.
  3. Final Answer:

    Use JSONDecoder().decode(Response.self, from: jsonData) -> Option C
  4. Quick Check:

    Decode top-level struct = Use JSONDecoder().decode(Response.self, from: jsonData) [OK]
Hint: Decode to the struct matching JSON root [OK]
Common Mistakes:
  • Decoding to nested User instead of Response
  • Using JSONEncoder instead of JSONDecoder
  • Using JSONSerialization instead of Codable
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