Created
June 13, 2023 21:57
-
-
Save adam-zethraeus/5358665f3ff76164614b6913e68a9b1b to your computer and use it in GitHub Desktop.
AnyEncodable — a type erased Encodable wrapper
This file contains 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 { | |
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