To make a struct codable in Swift, you need to conform to the Codable
protocol. This protocol combines the Encodable
and Decodable
protocols, which means the Codable struct can encode and decode itself.
Here is an example of a Person
struct that conforms to the Codable
protocol:
main.swift95 chars6 lines
To encode this struct to JSON, you'll need to create a JSONEncoder
and call its encode
method:
main.swift140 chars4 lines
To decode a JSON data to this struct, you'll need to create a JSONDecoder
and call its decode
method:
main.swift101 chars3 lines
The Person.self
parameter tells the decoder what type to decode the JSON data to.
gistlibby LogSnag