3

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?

Paulw11
  • 108,386
  • 14
  • 159
  • 186
Leem
  • 17,220
  • 36
  • 109
  • 159
  • 2
    Make icon an optional; since it is non-optional and can't be decoded it will be impossible for the decoder to create an instance of your struct – Paulw11 Sep 04 '18 at 11:30

1 Answers1

4

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.

Paulw11
  • 108,386
  • 14
  • 159
  • 186
  • That's correct (and also reopening the question – sorry for misreading the question!). Assigning `nil` however is not necessary for optionals, they have `nil` as initial value by default. – Martin R Sep 04 '18 at 11:49
  • Normally that is true, however in this case if you don't explicitly assign an initial value you get an error that Decodable can't synthesize an initialiser because it will try and decode UImage – Paulw11 Sep 04 '18 at 20:36
  • Hmm. I was using a Playground on my iPad as that is what I had to hand and it definitely needs the `= nil`. – Paulw11 Sep 04 '18 at 20:38