Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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