Skip to content

Instantly share code, notes, and snippets.

@ketzusaka
Created October 23, 2015 17:30
Show Gist options
  • Select an option

  • Save ketzusaka/6ce4731c8eef9f2c984d to your computer and use it in GitHub Desktop.

Select an option

Save ketzusaka/6ce4731c8eef9f2c984d to your computer and use it in GitHub Desktop.
Associated enums with Cereal
enum Job {
case Mechanic(String)
case Carpenter(String)
}
extension Job: CerealType {
private struct Keys {
static let job = "job"
static let name = "name"
}
init(decoder: CerealDecoder) throws {
guard let jobType: Int = try decoder.decode(Keys.job), name: String = try decoder.decode(Keys.name) else {
throw CerealError.InvalidEncoding
}
switch jobType {
case 1: self = .Mechanic(name)
case 2: self = .Carpenter(name)
default: throw CerealError.InvalidEncoding
}
}
func encodeWithCereal(inout encoder: CerealEncoder) throws {
switch self {
case .Mechanic(let mechanic):
try encoder.encode(1, forKey: Keys.job)
try encoder.encode(mechanic, forKey: Keys.name)
case .Carpenter(let carpenter):
try encoder.encode(2, forKey: Keys.job)
try encoder.encode(carpenter, forKey: Keys.name)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment