Skip to content

Instantly share code, notes, and snippets.

@Winchariot
Created December 14, 2017 16:05
Show Gist options
  • Save Winchariot/5665d5d188543f13cdef581ebe7783a6 to your computer and use it in GitHub Desktop.
Save Winchariot/5665d5d188543f13cdef581ebe7783a6 to your computer and use it in GitHub Desktop.
Encodable enum with associated values - single value container
//Encoding an enum with associated values is super simple.
enum Answer {
case rating(Int)
case freetextResponse(String)
}
extension Answer: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case let .rating(value):
try container.encode(value)
case let .freetextResponse(text):
try container.encode(text)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment