Skip to content

Instantly share code, notes, and snippets.

@byaruhaf
Forked from krzyzanowskim/JSONCodable.swift
Created January 6, 2020 01:14
Show Gist options
  • Save byaruhaf/d2cb624b915d4c3d070d0b19f6a21e7d to your computer and use it in GitHub Desktop.
Save byaruhaf/d2cb624b915d4c3d070d0b19f6a21e7d to your computer and use it in GitHub Desktop.
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