13

到目前为止我还没有弄清楚或能够在网上找到的东西。

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

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

{“名称”:“名称1”,“网址”:“www.google.com/randomImage”}

但是说我想向包含可解码的结构添加一个 UIImage 变量,例如

struct Example1: Decodable {
    var name: String?
    var url: String?
    var urlImage: UIImage? //To add later
}

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

4

2 回答 2

23

要排除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`
}

在 Swift 4.1 之前,这只有在添加= 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!
    }
于 2017-09-07T21:05:13.017 回答
1

实际上,我会让 urlImage 成为一个惰性变量。这样您就不必担心修改编码键。你所要做的就是写你的吸气剂,就像这样......

struct Example1 : Decodable {

    var name : String?
    var url  : URL?    // Better than String

    lazy var urlImage: UIImage? = {
        // Put your image-loading code here using 'url'
    }()
}
于 2018-07-11T21:39:36.390 回答