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

使用类继承是否会破坏类的可解码性。例如下面的代码


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 Development


print(item.id ?? "id is nil")

print(item.name ?? "name is nil") here

输出为:


1

name 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 Development


print(item.id ?? "id is nil")

print(item.name ?? "name is nil")

输出为:


id is nil

Large Building Development

而且您不能在两个类中都表示Codable。


慕尼黑5688855
浏览 372回答 3
3回答

素胚勾勒不出你

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}
打开App,查看更多内容
随时随地看视频慕课网APP