Skip to content

Instantly share code, notes, and snippets.

@minacle
Created March 26, 2019 14:01
Show Gist options
  • Save minacle/b7c154560f1770f559c89cc6cfaf1004 to your computer and use it in GitHub Desktop.
Save minacle/b7c154560f1770f559c89cc6cfaf1004 to your computer and use it in GitHub Desktop.
public enum StringOrValue<Value>: Codable
where Value: Codable {
case string(String)
case value(Value)
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = .string(try container.decode(String.self))
}
catch {
self = .value(try container.decode(Value.self))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .string(let string):
try container.encode(string)
case .value(let value):
try container.encode(value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment