Sometimes data from the internet or files needs special rules to be read correctly. Custom decoder configuration helps you tell your app how to understand that data.
Custom decoder configuration in iOS Swift
let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let object = try decoder.decode(MyType.self, from: jsonData)
You create a JSONDecoder instance to start decoding.
Use keyDecodingStrategy to change how keys are matched.
first_name to Swift properties like firstName.let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let user = try decoder.decode(User.self, from: data)
let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let event = try decoder.decode(Event.self, from: data)
struct AnyKey: CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) { self.stringValue = stringValue; self.intValue = nil }
init?(intValue: Int) { self.stringValue = ""; self.intValue = intValue }
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom { keys in
// Custom logic to change keys
return AnyKey(stringValue: keys.last!.stringValue.uppercased())!
}
let item = try decoder.decode(Item.self, from: data)This example shows how to decode JSON with snake_case keys into a Swift struct with camelCase properties using a custom decoder configuration.
import Foundation struct User: Decodable { let firstName: String let lastName: String } let json = "{\"first_name\": \"Jane\", \"last_name\": \"Doe\"}".data(using: .utf8)! let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let user = try decoder.decode(User.self, from: json) print("First name: \(user.firstName), Last name: \(user.lastName)")
Custom decoder settings help your app understand data that doesn't match your code exactly.
Always handle errors when decoding because data might be missing or wrong.
You can combine multiple strategies like key and date decoding for complex data.
Custom decoder configuration lets you control how data is read into your app.
Use it to fix mismatches between data keys and your code properties.
It makes your app more flexible and able to handle different data formats.
Practice
custom decoder configuration in Swift's Decodable protocol?Solution
Step 1: Understand the role of custom decoding
Custom decoder configuration allows you to specify how JSON or other data keys match your Swift properties.Step 2: Identify the purpose in data mapping
This helps fix mismatches when the data keys differ from your property names.Final Answer:
To control how data keys map to your code properties -> Option AQuick Check:
Custom decoding = data key mapping control [OK]
- Thinking it changes UI appearance
- Assuming it improves app speed
- Confusing decoding with encryption
Decodable struct?Solution
Step 1: Recall how to customize keys in Decodable
Swift uses an enum conforming toCodingKeyto map JSON keys to property names.Step 2: Identify the correct syntax
The enum cases represent the JSON keys, allowing custom mapping.Final Answer:
Use an enum conforming toCodingKeywith cases matching JSON keys -> Option BQuick Check:
Custom keys = enum CodingKey [OK]
- Trying to override init() without parameters
- Using lazy vars for decoding
- Confusing UI annotations with decoding
userName after decoding?
struct User: Decodable {
let userName: String
enum CodingKeys: String, CodingKey {
case userName = "user_name"
}
}
let json = "{\"user_name\": \"Alice\"}".data(using: .utf8)!Solution
Step 1: Understand the custom key mapping
The JSON key "user_name" maps to the propertyuserNamevia the CodingKeys enum.Step 2: Decode the JSON data
The decoder reads "Alice" from "user_name" and assigns it touserName.Final Answer:
"Alice" -> Option DQuick Check:
Mapped key value = "Alice" [OK]
- Assuming property name must match JSON key exactly
- Expecting nil if names differ
- Thinking decoding fails without exact key match
struct Product: Decodable {
let id: Int
let name: String
enum CodingKeys: String, CodingKey {
case id
case productName
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .productName)
}
}Solution
Step 1: Check CodingKeys enum against properties
The propertynameexpects a key, but CodingKeys hasproductNamewhich does not match the property name.Step 2: Identify the mapping issue
SinceproductNameis not linked toname, decoding will fail or mismatch.Final Answer:
CodingKeys enum does not map 'name' property correctly -> Option CQuick Check:
Property-key mismatch = error [OK]
- Not mapping property names to keys
- Forgetting Decodable conformance
- Misusing decoder container creation
"first_name" and "last_name", but your Swift struct uses firstName and lastName. How do you configure your decoder to handle this mismatch efficiently?Solution
Step 1: Identify the key-property name mismatch
JSON keys use snake_case, but Swift properties use camelCase.Step 2: Use CodingKeys enum to map keys to properties
Define enum withfirstName = "first_name"andlastName = "last_name"to decode correctly.Step 3: Avoid renaming properties or manual parsing for cleaner code
This approach keeps your code clean and flexible.Final Answer:
Create aCodingKeysenum mappingfirstName = "first_name"andlastName = "last_name"-> Option AQuick Check:
Use CodingKeys for key mapping [OK]
- Renaming properties instead of mapping keys
- Parsing JSON manually instead of using Decodable
- Using irrelevant annotations like @objc
Ready to prove it?
Pass the test and this pattern moves unknown
