Skip to content

Instantly share code, notes, and snippets.

@adam-zethraeus
Created June 13, 2023 21:57
Show Gist options
  • Save adam-zethraeus/5358665f3ff76164614b6913e68a9b1b to your computer and use it in GitHub Desktop.
Save adam-zethraeus/5358665f3ff76164614b6913e68a9b1b to your computer and use it in GitHub Desktop.
AnyEncodable — a type erased Encodable wrapper
extension Encodable {
fileprivate func encode(to container: inout SingleValueEncodingContainer) throws {
try container.encode(self)
}
}
/// A wrapper allowing Encodable types to be encoded — even
/// when only references as an existential `any Encodable`.
///
/// source: https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/5
/// author: https://forums.swift.org/u/hamishknight/summary
public struct AnyEncodable: Encodable {
var value: any Encodable
public init(_ value: any Encodable) {
self.value = value
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try value.encode(to: &container)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment