Skip to content

Instantly share code, notes, and snippets.

@KaQuMiQ
Created March 21, 2022 15:01
Show Gist options
  • Save KaQuMiQ/e5be7d0ed98373c9a45030ce6a63e026 to your computer and use it in GitHub Desktop.
Save KaQuMiQ/e5be7d0ed98373c9a45030ce6a63e026 to your computer and use it in GitHub Desktop.
JSONEncoder + any Encodable
import Foundation
extension JSONEncoder {
public func encode(
any anyEncodable: any Encodable
) throws -> Data {
try self.encode(
JSONEncodingWrapper(encodable: anyEncodable)
)
}
}
fileprivate struct JSONEncodingWrapper: Encodable {
fileprivate var encodable: any Encodable
fileprivate init (
encodable: any Encodable
) {
self.encodable = encodable
}
fileprivate func encode(
to encoder: Swift.Encoder
) throws {
try encodable
.encode(
to: encoder
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment