-
-
Save byaruhaf/d2cb624b915d4c3d070d0b19f6a21e7d 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
import Foundation | |
protocol JSONEncodable: Encodable { } | |
extension JSONEncodable { | |
func toJSON() throws -> String? { | |
try String(data: JSONEncoder().encode(self), encoding: .utf8) | |
} | |
} | |
protocol JSONDecodable: Decodable { } | |
extension JSONDecodable { | |
static func from(json data: Data) throws -> Self { | |
try JSONDecoder().decode(Self.self, from: data) | |
} | |
} | |
protocol JSONCodable: JSONEncodable & JSONDecodable { } | |
// Usage | |
struct Filter: JSONEncodable { | |
let id: String | |
} | |
let jsonString = Filter(id: "foo").toJSON() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment