相关疑难解决方法(0)

在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
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)

swift swift4 codable

59
推荐指数
6
解决办法
2万
查看次数

标签 统计

codable ×1

swift ×1

swift4 ×1