Last active
December 14, 2017 16:06
-
-
Save Winchariot/1491ece1e9054d241d36236020cf8c48 to your computer and use it in GitHub Desktop.
Encodable enum with associated values - keyed container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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