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?
Codable
toColor
? – Clueenum 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