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