Swift - 如何使这个结构符合 Codable?
Swift - How to conform this struct to Codable?
我有这个结构
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 个错误:
Type 'Photo' does not conform to protocol 'Decodable'
Type 'Photo' does not conform to protocol 'Encodable'
'Photo' 不符合协议 Encodable/Decodable 因为 UIImage 不能符合 Codable。另外 CLLocationCoordinate2D
不能符合 Codable。
您可以使用 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"
}
我有这个结构
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 个错误:
Type 'Photo' does not conform to protocol 'Decodable'
Type 'Photo' does not conform to protocol 'Encodable'
'Photo' 不符合协议 Encodable/Decodable 因为 UIImage 不能符合 Codable。另外 CLLocationCoordinate2D
不能符合 Codable。
您可以使用 Data
类型指定 var image
,然后从 Data
.
像这样:
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"
}