是否应该使用类继承来破坏类的可解码性.例如,以下代码
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
Run Code Online (Sandbox Code Playgroud)
输出是:
1
name is nil
Run Code Online (Sandbox Code Playgroud)
现在,如果我反转这个,名称解码但id没有.
class Server {
var id : Int?
}
class Development : Server, Codable {
var …Run Code Online (Sandbox Code Playgroud)