使用类继承是否会破坏类的可解码性。例如下面的代码class Server : Codable { var id : Int?}class Development : Server { var name : String? var userId : Int?}var json = "{\"id\" : 1,\"name\" : \"Large Building Development\"}"let jsonDecoder = JSONDecoder()let item = try jsonDecoder.decode(Development.self, from:json.data(using: .utf8)!) as Developmentprint(item.id ?? "id is nil")print(item.name ?? "name is nil") here输出为:1name is nil现在,如果我将其反转,则名称会解码,而id不会。class Server { var id : Int?}class Development : Server, Codable { var name : String? var userId : Int?}var json = "{\"id\" : 1,\"name\" : \"Large Building Development\"}"let jsonDecoder = JSONDecoder()let item = try jsonDecoder.decode(Development.self, from:json.data(using: .utf8)!) as Developmentprint(item.id ?? "id is nil")print(item.name ?? "name is nil")输出为:id is nilLarge Building Development而且您不能在两个类中都表示Codable。
3 回答
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
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)
}
对于解码,我这样做:
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let values = try decoder.container(keyedBy: CodingKeys.self)
total = try values.decode(Int.self, forKey: .total)
}
private enum CodingKeys: String, CodingKey
{
case total
}
- 3 回答
- 0 关注
- 410 浏览
添加回答
举报
0/150
提交
取消