How do I make an enum codable?

Viewed 3558

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?

1 Answers
struct Person: Codable {
     var firstName: String
     var lastName: String
     var favoriteColor: Color
}

enum Color: String, Codable {
   case blue, red, green, yellow, pink, purple
}
Related