How to create your own Encoder/Decoder in Swift: The UserInfo
This is the second part of the encoder/decoder serie. The first part can be found here. This serie explains how to build your own Encoder/Decoder.
What is userInfo?
Apple’s documentation states:
Any contextual information set by the user for encoding/decoding.
The Encoder or Decoder will just give access to the userInfo but does not use it in its implementation. It can be used by the user to make encoding and decoding decisions based on the values it passes with it.
How to use userInfo in Encodable?
Let’s say we have a Person
with a name
and we want to introduce a strategy that will capitalize the first letter of each part of the name.
Our code, without the implementations, looks as follows:
struct Person: Encodable {
let name: String
enum CodingKeys: CodingKey {
case name
}
func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.name, forKey: .name)
}
}
let person = Person(name: "christopher robin")
do {
let encoder = JSONEncoder()
let jsonData = try…