Swift 4 Decodable - Additional Variables

点点圈 提交于 2019-12-01 03:40:50
andyvn22

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

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.

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

Actually, I'd make urlImage a lazy var. That way you don't have to worry about modifying the coding keys. All you have to do is write your getter, like so...

struct Example1 : Decodable {

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

    lazy var urlImage: UIImage? = {
        // Put your image-loading code here using 'url'
    }()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!