Just as we used the Decodable
protocol to convert data into our objects, we can do the reverse conversion using the Encodable
protocol.
struct Person: Encodable {
let name: String
let age: Int
}
let person: Person = Person(name: "Pablo", age: 23)
let data: Data? = try? JSONEncoder().encode(person)
If you want to use both the
Decodable
and Encodable
protocols in the same object, you can simply use the Codable
protocol, which includes both.
Be the first to comment