Sergio Bost
Sergio Bost

Reputation: 3209

Lost my conformance to Codable after adding an enum

So I have a struct that is Codable ( or was )

struct Person  { 
    let name: String           //<-- Fine
    let age: Int               //<-- Fine
    let location: String       //<-- Fine

    let character: Character.  //<-- Here comes the error (Type Person does not conform to Decodable)
 
}

enum Character {
    case nice, rude 
}

Now I understand the error. Every type except the enum is Codable so I'm good up until that point. Now as a way to solve this.. I was pretty sure this would work ..

extension Person { 
  private enum CodingKeys: CodingKey { case name, age, location } 
 }

But even after telling Swift the properties I want to be decoded I still get this error? Puzzled.

Upvotes: 3

Views: 486

Answers (1)

Sweeper
Sweeper

Reputation: 270890

Since you excluded character from the keys to decode, you need to give character an initial value. After all, all properties need to be initialised to some value during initialisation.

The easiest way to do this is to give the initial value of nil:

let character: Character? = nil

Of course, you can also do:

let character: Character = .rude

Also note that you can make the enum Codable, simply by giving it a raw value type:

enum Character: Int, Codable {
    // now nice will be encoded as 0, and rude will be encoded as 1
    case nice, rude
}

Upvotes: 3

Related Questions