Skip to content

Instantly share code, notes, and snippets.

@asmallteapot
Created June 26, 2017 16:25
Show Gist options
  • Save asmallteapot/1cef51f8c8d8f1c929bb168cf7ce8adb to your computer and use it in GitHub Desktop.
Save asmallteapot/1cef51f8c8d8f1c929bb168cf7ce8adb to your computer and use it in GitHub Desktop.
Code koan: Trivial extension to `URLSession` for decoding responses with `Decodable` in Swift 4
import Foundation
public protocol DataDecoder {
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
}
extension JSONDecoder: DataDecoder {}
extension PropertyListDecoder: DataDecoder {}
extension URLSession {
public func dataTask<T>(with request: URLRequest,
decodedAs decodableType: T.Type,
using decoder: DataDecoder,
completionHandler: @escaping (T?, URLResponse?, Error?) -> Void
) -> URLSessionDataTask where T: Decodable {
return self.dataTask(with: request, completionHandler: { (data, response, error) in
var decoded: T? = nil
if let data = data {
// TODO: don't drop this error
decoded = try? decoder.decode(decodableType, from: data)
}
completionHandler(decoded, response, error)
})
}
}
import Foundation
struct Book: Codable {
let author: String
let title: String
let yearReleased: Int
}
let request: URLRequest! = nil
let task = URLSession.shared.dataTask(with: request, decodedAs: Book.self, using: decoder) {
book, _, _ in
print(book ?? "nil")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment