Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created May 10, 2019 13:03
Show Gist options
  • Save chriseidhof/bed84f040c37af503b7b67c444193d34 to your computer and use it in GitHub Desktop.
Save chriseidhof/bed84f040c37af503b7b67c444193d34 to your computer and use it in GitHub Desktop.
import Foundation
struct Resource<A> {
var request: URLRequest
var parse: (Data) throws -> A
}
extension Resource where A: Decodable {
init(get url: URL) {
self.init(request: URLRequest(url: url)) { data in
try JSONDecoder().decode(A.self, from: data)
}
}
}
extension URLSession {
func load<A>(_ r: Resource<A>, callback: @escaping (Result<A, Error>) -> ()) {
dataTask(with: r.request) { data, response, err in
callback(Result {
if let e = err { throw e }
guard let d = data else { fatalError() }
return try r.parse(d)
})
}.resume()
}
}
struct Country: Codable {
var alpha2Code: String
var name: String
var population: Int
}
let sample = Resource<[Country]>(get: URL(string: "https://restcountries.eu/rest/v2/all")!)
URLSession.shared.load(sample) { res in print(res) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment