Make class conforming to Codable by default in Swift

与世无争的帅哥 提交于 2019-12-07 02:16:26

Here's a good blog post which includes an answer to your question: source

Scroll down to inheritance and you'll see the following:

Assuming we have the following classes:

class Person : Codable {
    var name: String?
}

class Employee : Person {
    var employeeID: String?
}

We get the Codable conformance by inheriting from the Person class, but what happens if we try to encode an instance of Employee?

let employee = Employee()
employee.employeeID = "emp123"
employee.name = "Joe"

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try! encoder.encode(employee)
print(String(data: data, encoding: .utf8)!)

{
  "name" : "Joe"
}

This is not the expected result, so we have to add a custom implementation like this:

class Person : Codable {
    var name: String?

    private enum CodingKeys : String, CodingKey {
        case name
    }

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

Same story for the subclass:

class Employee : Person {
    var employeeID: String?

    private enum CodingKeys : String, CodingKey {
        case employeeID = "emp_id"
    }

    override func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(employeeID, forKey: .employeeID)
    }
}

The result would be:

{
  "emp_id" : "emp123"
}

Which again is not the expected result, so here we are using inheritance by calling super.

// Employee.swift
    override func encode(to encoder: Encoder) throws {
        try super.encode(to: encoder)
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(employeeID, forKey: .employeeID)
    }

Which finally gives us what we really wanted from the beginning:

{
    "name": "Joe",
    "emp_id": "emp123"
}

If you're not happy with the flattened result, there's a tip on how to avoid that too.

All the credits to the guy who wrote the blog post and my thanks. Hope it helps you as well, cheers!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!