Last active
August 17, 2022 04:16
-
-
Save drekka/a3283d5f00d8ec54c398c92782a50609 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
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