How do I make an enum codable? [duplicate]
Asked Answered
A

1

5

I have a nested an enum inside a struct that I want to conform to Codable. How do I make the enum codable and therefore make the struct codable?

Here is an example of what I have:

struct Person: Codable {
  var firstName: String
  var lastName: String 
  var favoriteColor: Color

  enum Color {
    case blue, red, green, yellow, pink, purple
  }
}

Then, I get two errors :

Type 'Person' does not conform to protocol 'Decodable'

Type 'Person' does not conform to protocol 'Encodable'

How can I fix this problem?

Edit

I have also tried conforming Color to Codable. Xcode adds these protocol stubs:

init(from decoder: Decoder) throws {
  <#code#>
}
func encode(to encoder: Encoder) throws {
  <#code#>
}

What would I do with this?

Autoplasty answered 31/3, 2020 at 18:12 Comment(5)
Have you tried adding Codable to Color?Clue
Do you mean conforming Color to the Codable protocol?Autoplasty
How would I do that?Autoplasty
enum Color: String, Codable (or whatever raw value you want to use). If you don't want to use a codable-friendly raw value then you will have to implement the decode/encode yourself.Clue
#44581219Lacey
M
8
struct Person: Codable {
     var firstName: String
     var lastName: String
     var favoriteColor: Color
}

enum Color: String, Codable {
   case blue, red, green, yellow, pink, purple
}
Meijer answered 31/3, 2020 at 18:15 Comment(5)
What does this do with my Color enum? Does this modify it in any way?Autoplasty
It declares that the Color enum value is a StringCotopaxi
Just a note: the enum need not be declared inside the struct declaration.Vanadium
@Vanadium you are absolutely right, thanks for mentioning it. I edited my answer.Cotopaxi
Note there's nothing wrong with it being defined inside the struct either. Really depends on the context. If this enum is specific to Person it might as well be nested.Clue

© 2022 - 2024 — McMap. All rights reserved.