让我的简单结构在 Swift 4 中可编码不起作用

Make my simple struct codable in Swift 4 doesn't work

我是 Swift4 的新手。我正在尝试使用 Codable 使我的 struct 类型对象可编码和可解码为 JSON。

这是我的 struct Product:

// 我声明它符合 codable

public struct Product: Codable {
  public let name: String
  public var isSold: Bool
  public let icon: UIImage // problem is here

  …

  // I have excluded 'icon' from codable properties
  enum CodingKeys: String, CodingKey {
        case name
        case isSold = “is_sold”
    }
}

编译器告诉我错误:'UIImage’ doesn’t conform to ‘Decodable’,但我已经定义了 CodingKeys,它应该告诉我希望哪些属性是可编码的,并且我已经排除了 UIImage 属性。

我认为这样编译器不会抱怨 UIImage 类型,但它仍然抱怨。如何摆脱这个错误?

因为UIImage无法解码并且没有默认值,Decodable协议不可能合成初始化器。

如果您将 icon 设为可选 UIImage 并将 nil 指定为默认值,您将能够从 JSON 中解码结构的其余部分。

public struct Product: Codable {
    public let name: String
    public var isSold: Bool
    public var icon: UIImage? = nil 
    enum CodingKeys: String, CodingKey {
        case name
        case isSold = "is_sold"
    }
}

您也可以将其设为非可选并指定一个占位符图像。

注意,根据 Swift 版本,您可能不需要 = nil 初始值。