Swift Codable: Decoding / Encoding With Context
The Codable
protocols are one of the coolest recent additions to Swift. Even though it works similarly to its community counterparts like Unbox
, Codable
has the advantage of being powered by the compiler.
One of my favorite features in Unbox
was to give a context to the decoding operation. Let's take a look at how we can achieve the same with Codable
.
Example 1: Giving different values to the same property
Decoding with "context" refers to the ability to change how types are decoded depending on what's going on in your app. Let's say that our app is sending a request asking for information regarding a header that should be displayed on the screen, with our app locally storing an additional textColor
property into the model:
struct HeaderInformation: Decodable {
let title: String
let imageUrl: String
var textColor: UIColor {
return .black
}
}
Now, imagine the following situation: What if we want textColor
to be different depending on which screen such header is being presented? For example, displaying headers on the app's home could have a green text, while headers at the profile screen could be blue.
There are multiple ways to achieve this, but let's focus on Codable
. Codable
allows you to provide context to a JSONDecoder
/JSONEncoder
through their userInfo
property:
/// Contextual user-provided information for use during decoding.
open var userInfo: [CodingUserInfoKey : Any]
The CodingUserInfoKey
is a RawRepresentable
string enum, so you can add pretty much anything to userInfo
. When this is done, the same userInfo
values will be accessible as part of the inner Decoder
/Encoder
instance:
struct HeaderInformation: Decodable {
let title: String
let imageUrl: String
let textColor: UIColor
static var textColorUserInfoKey: CodingUserInfoKey {
return CodingUserInfoKey(rawValue: "textColor")!
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
title = try container.decode(String.self, forKey: .title)
imageUrl = try container.decode(String.self, forKey: .imageUrl)
textColor = decoder.userInfo[Self.textColorUserInfoKey] as? UIColor ?? .black
}
}
To make this work, simply fill the userInfo
dictionary before decoding the data.
let decoder = JSONDecoder()
decoder.userInfo[HeaderInformation.textColorUserInfoKey] = UIColor.red
let headerInfo = decoder.decode(HeaderInformation.self, from: data)
CodingUserInfoKey
requires force-unwrapping because it is RawRepresentable
, but doing so will never result in a crash. To hide it, I like to abstract it inside an extension that takes a regular String
instead:
extension Decoder {
func getContext(forKey key: String) -> Any? {
let infoKey = CodingUserInfoKey(rawValue: key)!
return userInfo[infoKey]
}
}
extension JSONDecoder {
func set(context: Any?, forKey key: String) {
let infoKey = CodingUserInfoKey(rawValue: key)!
userInfo[infoKey] = context
}
}
We can now use the type's own CodingKeys
as the userInfo key, resulting in the following improvements:
let key = HeaderInformation.CodingKeys.textColor.stringValue
decoder.set(context: UIColor.red, forKey: key)
//
textColor = decoder.getContext(forKey: CodingKeys.textColor.stringValue)
Example 2: Powering modularized type-erased structs
One cool example of how I use Codable
contexts is how AnyRoute
works in the RouterService library:
/// A type-erased container for a `Route`, used for route decoding purposes.
public struct AnyRoute {
public let value: Route
public let routeString: String
}
In short, we have the following environment:
- Apps can define their own "routes", which are structs used to navigate between screens.
- These routes are registered into a RouterService
instance, which receives said routes and pushes the related view controllers.
- Routes can be decoded from a specific string format, allowing your backend to dictate which screen the app should navigate to.
The latter is done through AnyRoute
-- an erased Route
type that knows how to decode such string format into the actual Route
type defined by the app. The problem is: because AnyRoute is defined inside the RouterService library, it has no access to the app's Routes. How can it decode the correct Route type?
This can be achieved by using Codable
's context features. Because Routes
have to be registered in the main RouterService
instance, we can inject it into the decoding operation and have it determine which Route
should be decoded:
extension AnyRoute: Decodable {
static var contextUserInfoKey: CodingUserInfoKey {
// swiftlint:disable:next force_unwrapping
return CodingUserInfoKey(rawValue: "routerservice_anyroute_context")!
}
public init(from decoder: Decoder) throws {
let ctx = decoder.userInfo[AnyRoute.contextUserInfoKey]
guard let context = ctx as? RouterServiceAnyRouteDecodingProtocol else {
preconditionFailure("TRIED TO DECODE ANYROUTE WITHOUT A CONTEXT!")
}
let data = try context.decodeAnyRoute(fromDecoder: decoder)
self.value = data.0
self.routeString = data.1
}
}
public protocol RouterServiceAnyRouteDecodingProtocol {
func decodeAnyRoute(fromDecoder decoder: Decoder) throws -> (Route, String)
}
Assuming that RouterService
was injected into the JSONDecoder
, the decoding operation will be deferred to it:
extension RouterService: RouterServiceAnyRouteDecodingProtocol {
public func decodeAnyRoute(fromDecoder decoder: Decoder) throws -> (Route, String) {
let container = try decoder.singleValueContainer()
let identifier = try container.decode(String.self)
guard let routeString = RouteString(fromString: identifier) else {
throw RouteDecodingError.failedToParseRouteString
}
guard let routeType = registeredRoutes[routeString.scheme]?.0 else {
throw RouteDecodingError.unregisteredRoute
}
do {
let value = try routeType.decode(JSONDecoder(), routeString.parameterData)
return (value, routeString.originalString)
} catch {
throw error
}
}
public enum RouteDecodingError: Swift.Error {
case unregisteredRoute
case failedToParseRouteString
}
}
This decentralized behavior is especially important for modular apps (which is RouterService
's use case), as different targets can reference and decode AnyRoutes
without having access to the app's real Routes
.