3

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.

2
  • 1
    You just need this enum Character: String, Codable Commented Jul 8, 2021 at 6:23
  • 3
    Consider not calling your enum Character - there is already a type called Character for single letters in Strings. Or you might nest Character inside Person so then you would have Swift.Character and Person.Character Commented Jul 8, 2021 at 9:48

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.