Leem
Leem

Reputation: 18308

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

I am new in Swift4. I am trying to use Codable to make my struct type object encodable & decodable to JSON.

Here is my struct Product:

// I declare it to conform to 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”
    }
}

Compiler tells me error : 'UIImage’ doesn’t conform to ‘Decodable’, but I have defined CodingKeys which is supposed to tell which properties are wished to be codable, and I have excluded the UIImage property.

I thought this way the compiler wouldn't complain that UIImage type, but it still complains. How to get rid of this error?

Upvotes: 3

Views: 833

Answers (1)

Paulw11
Paulw11

Reputation: 114856

Because UIImage can't be decoded and it doesn't have a default value, it isn't possible for the Decodable protocol to synthesise an initialiser.

If you make icon an optional UIImage and assign nil as a default value you will be able to decode the rest of the struct from 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"
    }
}

You could also make it non-optional and assign a placeholder image.

Note, depending on the Swift version you may not need the = nil initial value.

Upvotes: 4

Related Questions