Skip to content

Instantly share code, notes, and snippets.

@Winchariot
Last active December 14, 2017 16:06
Show Gist options
  • Save Winchariot/1491ece1e9054d241d36236020cf8c48 to your computer and use it in GitHub Desktop.
Save Winchariot/1491ece1e9054d241d36236020cf8c48 to your computer and use it in GitHub Desktop.
Encodable enum with associated values - keyed container
enum QuestionnaireFeedback {
case numeric(Int)
case text(String)
}
extension QuestionnaireFeedback: Encodable {
enum CodableKeys: String, CodingKey {
case numeric
case text
}
//The only real trick to encoding enums with associated values is implementing the encode func yourself.
// Make + use the CodableKeys helper enum to help map your QuestionnaireFeedback instance to the correct case/associated value
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodableKeys.self)
switch self {
case let .numeric(value):
try container.encode(value, forKey: .numeric)
case let .text(text):
try container.encode(text, forKey: .text)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment