Skip to content

Instantly share code, notes, and snippets.

@timvermeulen
Last active August 2, 2018 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timvermeulen/ab4ff698dada76f1453751055e3af34c to your computer and use it in GitHub Desktop.
Save timvermeulen/ab4ff698dada76f1453751055e3af34c to your computer and use it in GitHub Desktop.
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