Covering the Codable protocol
The Codable protocol is an important Swift feature that allows us to convert serialized data such as a string to a data structure we can work with.
The first thing to know about the Codable protocol is that it combines two other protocols – “Encodable” and “Decodable.” These two protocols help us to convert data both ways.
Data objects (such as structs) need to conform to the Codable protocol so that we can convert them back and forth.
Here’s a simple code snippet:
struct Person: Codable { var name: String var age: Int var address: String } let person = Person(name: "John", age: 30, address: "123 Main St.") let encoder = JSONEncoder() let data = try encoder.encode(person) let decoder = JSONDecoder() let person = try decoder.decode(Person.self, from: data)
As we can see in the preceding code block, Person
conforms...