我有以下结构体...
struct Photo: Codable {
let hasShadow: Bool
let image: UIImage?
enum CodingKeys: String, CodingKey {
case `self`, hasShadow, image
}
init(hasShadow: Bool, image: UIImage?) {
self.hasShadow = hasShadow
self.image = image
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
hasShadow = try container.decode(Bool.self, forKey: .hasShadow)
// This fails
image = try container.decode(UIImage?.self, forKey: .image)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(hasShadow, forKey: .hasShadow)
// This also fails
try container.encode(image, forKey: .image)
}
}
编码照片
失败,错误信息为...
可选项不符合可编码协议,因为UIImage不符合可编码协议
解码失败,错误信息为...
在期望非可选类型Optional的编码键“image”时未找到该键
是否有一种方法可以对包含符合NSCoding
协议的NSObject
子类属性(例如UIImage
、UIColor
等)的Swift对象进行编码?
Data
。请查阅 编码和解码自定义类型。 - vadian