
The goal
KeyedCodable is an addition to swift's Codable and it's designed for automatic nested key mappings. The goal it to avoid manual implementation of Encodable/Decodable and make encoding/decoding easier, more readable, less boilerplate and what is the most important fully compatible with 'standard' Codable.
Nested keys
First, please have a look on Codable example provided by Apple.
vanilla Codable:
struct Coordinate {
var latitude: Double
var longitude: Double
var elevation: Double
enum CodingKeys: String, CodingKey {
case latitude
case longitude
case additionalInfo
}
enum AdditionalInfoKeys: String, CodingKey {
case elevation
}
}
extension Coordinate: Decodable {
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
latitude = try values.decode(Double.self, forKey: .latitude)
longitude = try values.decode(Double.self, forKey: .longitude)
let additionalInfo = try values.nestedContainer(keyedBy: AdditionalInfoKeys.self, forKey: .additionalInfo)
elevation = try additionalInfo.decode(Double.self, forKey: .elevation)
}
}
extension Coordinate: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(latitude, forKey: .latitude)
try container.encode(longitude, forKey: .longitude)
var additionalInfo = container.nestedContainer(keyedBy: AdditionalInfoKeys.self, forKey: .additionalInfo)
try additionalInfo.encode(elevation, forKey: .elevation)
}
}
KeyedCodable:
struct Coordinate: Codable {
var latitude: Double
var longitude: Double
var elevation: Double
enum CodingKeys: String, KeyedKey {
case latitude
case longitude
case elevation = "additionalInfo.elevation"
}
}
By default dot is used as delimiter to separate the inner keys
@Flat classes
Flat classes feature allows you to group properties into smaller parts. In the example below you can see that:
- longitude and latitude are placed in json's main class but it is 'moved' into separate struct
Location in the swift's model
- both longitude and latitude are optional. If any of them is missing, the location property will be nil.
Example JSON:
{
"longitude": 3.2,
"latitude": 3.4,
"greeting": "hallo"
}
KeyedCodable:
struct InnerWithFlatExample: Codable {
@Flat var location: Location?
let greeting: String
}
struct Location: Codable {
let latitude: Double
let longitude: Double
}
Without property wrappers
struct InnerWithFlatExample: Codable {
let location: Location?
let greeting: String
enum CodingKeys: String, KeyedKey {
case greeting
case location = ""
}
}
By default empty string or whitespaces are used to mark flat class
@Flat arrays
Probably you found out that decoding an array will fail if decoding of any array's element fails. Flat array KeyedCodable's feature omits incorrect elements and creates array that contain valid elements only. In example below array property will contain three elements [1,3,4] though decoding second element fails.
{
"array": [
{
"element": 1
},
{},
{
"element": 3
},
{
"element": 4
}
]
}
KeyedCodable:
struct OptionalArrayElementsExample: Codable {
@Flat var array: [ArrayElement]
}
struct ArrayElement: Codable {
let element: Int
}
Without property wrappers
struct OptionalArrayElementsExample: Codable {
let array: [ArrayElement]
enum CodingKeys: String, KeyedKey {
case array = ".array"
}
}
To enable flat array you have to add [flat][delimiter] before property name - by defult it is 'empty string + dot'
KeyOptions
In case of conflicts between json's keys and delimiters used by KeyedCodable, you may use KeyOptions to configure mapping features. You may do that by providing options: KeyOptions? property in your CodingKeys ( use nil to use default value). You may also disable the feature by setting .none value.
Examples
Example JSON:
{
"* name": "John",
"": {
".greeting": "Hallo world",
"details": {
"description": "Its nice here"
}
},
"longitude": 3.2,
"latitude": 3.4,
"array": [
{
"element": 1
},
{},
{
"element": 3
},
{
"element": 4
}
],
"* array1": [
{
"element": 1
},
{},
{
"element": 3
},
{
"element": 4
}
]
}
KeyedCodable:
struct KeyOptionsExample: Codable {
let greeting: String
let description: String
let name: String
let location: Location
let array: [ArrayElement]
let array1: [ArrayElement]
enum CodingKeys: String, KeyedKey {
case location = "__"
case name = "* name"
case greeting = "+.greeting"
case description = ".details.description"
case array = "### .array"
case array1 = "### .* array1"
var options: KeyOptions? {
switch self {
case .greeting: return KeyOptions(delimiter: .character("+"), flat: .none)
case .description: return KeyOptions(flat: .none)
case .location: return KeyOptions(flat: .string("__"))
case .array, .array1: return KeyOptions(flat: .string("### "))
default: return nil
}
}
}
}
@Zero as default value
@Zero feature sets default "zero" value for the property in case value is not set in the JSON (no key at all or null value is set). If you find the situation there is no difference between 0 and nil from the business perspective you can easily get rid off optional from your codable.
Example JSON:
KeyedCodable:
struct ZeroTestCodable: Codable {
var name: String // Jan
@Zero var secondName: String // "" - empty string
@Zero var numberOfChildren: Int // 0
@Zero var point: Point // Point(x: 0.0, y: 0.0)
}
struct Point: Codable {
let x: Float
let y: Float
}
Transformers - @CodedBy, @EncodedBy, @DecodedBy