【问题标题】:Swift - How to conform this struct to Codable?Swift - 如何使这个结构符合 Codable?
【发布时间】:2020-02-13 13:51:03
【问题描述】:

我有这个结构

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 个错误:

类型“照片”不符合协议“可解码”

类型“照片”不符合协议“可编码”

【问题讨论】:

  • UIImage 应该是 Codable,但它不是。 CLLocationCoordinate2D 也必须是 Codable。另外CodingKeys 必须是Photo 的内部成员。在这种情况下,根本不需要它们。您最好的选择是通过转换为 Data (png/jpeg) 并可能转换为 StringUIImage 进行自定义编码/解码。

标签: ios swift xcode codable


【解决方案1】:

'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"
}

【讨论】:

  • 请注意,将图像数据作为 JSON 字符串发送会非常慢,而且它的大小也会大大增加。我只会对图像 URL 进行编码。关于位置,创建一个位置结构会更好。 struct Location: Codable { let latitude, longitude: Double }
猜你喜欢
  • 1970-01-01
  • 2018-02-22
  • 2019-05-12
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多