Created
March 26, 2019 14:01
-
-
Save minacle/b7c154560f1770f559c89cc6cfaf1004 to your computer and use it in GitHub Desktop.
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
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