Swift 4 Decodable-其他变量 [英] Swift 4 Decodable - Additional Variables

查看:119
本文介绍了Swift 4 Decodable-其他变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我还没有发现或可以在线找到的东西.

Something I havent figured out or have been able to find online as of yet.

是否可以将其他字段添加到包含可解码协议的结构中,而JSON数据中不存在该字段?

Is there a way to add additional fields onto a struct containing the decodable protocol in which are not present in the JSON Data?

例如,为了简单起见,我有一个这样构造的json对象数组

For example and simplicity, say I have an array of json objects structured as such

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

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

但是说我想向包含可解码的结构(例如,

but say I want to add a UIImage variable to that struct containing the decodable such as

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

是否有一种方法可以实现可解码协议,以便从JSON获取名称和网址,但允许我稍后添加UIImage?

Is there a way to implement the decodable protocol in order to get the name and url from the JSON but allow me to add the UIImage later?

推荐答案

要排除urlImage,您必须手动遵循Decodable,而不是合成其要求:

To exclude urlImage you must manually conform to Decodable instead of letting its requirements be synthesized:

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的默认值假定为可选属性.

Before Swift 4.1 this only works if you add = nil to urlImage, even though the default value of nil is usually assumed for optional properties.

如果要在初始化时为urlImage提供值,而不是使用= nil,则还可以手动定义初始化程序:

If you want to provide a value for urlImage at initialization, rather than using = nil, you can also manually define the initializer:

    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!
    }

这篇关于Swift 4 Decodable-其他变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆