Swift 4可解码 - 附加变量

Ryk*_*uno 11 json struct swift swift4 decodable

我还没想到或者能够在网上找到的东西.

有没有办法将其他字段添加到包含JSON数据中不存在的可解码协议的结构中?

例如,简单,假设我有一个json对象的数组结构

{"name":"name1","url":"www.google.com/randomImage"}

但是我想要将UIImage变量添加到包含可解码的结构中,例如

struct Example1: Decodable {
    var name: String?
    var url: String?
    var urlImage: UIImage? //To add later
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现可解码协议,以便从JSON获取名称和URL,但允许我稍后添加UIImage?

and*_*n22 16

要排除urlImage您必须手动符合,Decodable而不是让它的要求合成:

struct Example1 : Decodable { //(types should be capitalized)
    var name: String?
    var url: URL? //try the `URL` type! it's codable and much better than `String` for storing URLs
    var urlImage: UIImage? //not decoded

    private enum CodingKeys: String, CodingKey { case name, url } //this is usually synthesized, but we have to define it ourselves to exclude `urlImage`
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,这仅在您添加时= nil有效urlImage,即使nil通常假定可选属性的默认值.如果要为urlImage初始化而不是使用提供值= nil,还可以手动定义初始化程序:

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        url = try container.decode(URL.self, forKey: .url)
        urlImage = //whatever you want!
    }
Run Code Online (Sandbox Code Playgroud)

  • 编译器实际上可以为你合成`init(from:)`.你只需要说'var urlImage:UIImage?= nil`以满足其对`CodingKeys`中未列出的属性的默认值的需要(为什么它不接受`nil`的隐式默认值我不太确定). (4认同)