为了账号安全,请及时绑定邮箱和手机立即绑定

在带有继承的Swift 4中使用Decodable

在带有继承的Swift 4中使用Decodable

慕尼黑5688855 2019-12-12 14:10:41
使用类继承是否会破坏类的可解码性。例如下面的代码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


}



查看完整回答
反对 回复 2019-12-13
  • 3 回答
  • 0 关注
  • 366 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信