我有这个结构
struct Photo: Codable {
var image: UIImage
let caption: String?
let location: CLLocationCoordinate2D?
}
private enum CodingKeys: String, CodingKey {
case image = "image"
case caption = "caption"
case location = "location"
}
我收到这 2 个错误:
类型"照片"不符合"可解码"协议
类型"照片"不符合"可编码"协议
'Photo' 不符合协议 Encodable/Decodable,因为 UIImage 无法符合 Codable。此外,CLLocationCoordinate2D
不能符合可编码。 您可以使用Data
类型指定var image
,然后从Data
获取 UIImage。
像这样:
struct Photo: Codable {
var imageData: Data
let caption: String?
let location: String?
func getImage(from data: Data) -> UIImage? {
return UIImage(data: data)
}
}
private enum CodingKeys: String, CodingKey {
case imageData = "image"
case caption = "caption"
case location = "location"
}