Last active
August 2, 2018 21:34
-
-
Save timvermeulen/ab4ff698dada76f1453751055e3af34c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
struct AnyEncodable: Encodable { | |
let base: Encodable | |
init(_ value: Encodable) { | |
base = value | |
} | |
func encode(to encoder: Encoder) throws { | |
try base.encode(to: encoder) | |
} | |
} | |
struct EncodableDictionary: Encodable { | |
private(set) var base: [String: AnyEncodable] = [:] | |
subscript(key: String) -> Encodable? { | |
get { return base[key]?.base } | |
set { base[key] = newValue.map(AnyEncodable.init) } | |
} | |
func encode(to encoder: Encoder) throws { | |
try base.encode(to: encoder) | |
} | |
} | |
extension EncodableDictionary: ExpressibleByDictionaryLiteral { | |
init(dictionaryLiteral elements: (String, Encodable?)...) { | |
for case let (key, value?) in elements { | |
base[key] = AnyEncodable(value) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment