Created
June 26, 2017 16:25
-
-
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
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 | |
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) | |
}) | |
} | |
} |
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 | |
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