Skip to content

Instantly share code, notes, and snippets.

@drekka
Last active August 17, 2022 04:16
Show Gist options
  • Save drekka/a3283d5f00d8ec54c398c92782a50609 to your computer and use it in GitHub Desktop.
Save drekka/a3283d5f00d8ec54c398c92782a50609 to your computer and use it in GitHub Desktop.
extension Encodable {
// This lets any encodable encode itself into a container.
fileprivate func encode(to container: inout SingleValueEncodingContainer) throws {
try container.encode(self)
}
}
// This wraps an encodable so it can be encoded. It uses the above extension so that the
// we don't have to know the encodable's type.
struct AnyEncodable : Encodable {
var value: Encodable
init(_ value: Encodable) {
self.value = value
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try value.encode(to: &container)
}
}
// Usage example, enum with an Encodable associated value.
enum A {
case b
case c(Encodable)
}
let b = A.b
let c = A.c(123)
if case A.c(let encodable) = c {
let result = try? JSONEncoder().encode(AnyEncodable(encodable))
String(data: result!, encoding: .utf8) // -> "123"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment