How To Conform To Codable Protocol

If you need a Class to conform to the Codable Protocol it must be both Encodable and Decodable.

For both of them you will need to have an enum of CodingKeys. In this example our class has an id, name, and score:

enum CodingKeys: String, CodingKey {
        case id
        case name
        case score

To conform to Encodable the encode method must be defined:

func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(name, forKey: .name)
        try container.encode(score, forKey: .score)

To conform to Decodable a special init method must be defined:

required init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(String.self, forKey: .id)
        name = try container.decode(String.self, forKey: .name)
        score = try container.decode(Int.self, forKey: .score)


Content is copyrighted 2019-2022 © D.S. Chapman. This site was built using GatsbyJS. Code for this website is open source and available on Github