In an article, I saw a code snippet like below:
extension URLSessionDataTask: Cancellable {}
extension URLSession: NetworkService {
public func fetchData(with request: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Void) -> AnyCancellable {
let task = dataTask(with: request, completionHandler: handler)
task.resume()
return AnyCancellable(task)
}
}
There are several things that I do not understand:
- What is the purpose of making URLSessionDataTask conform to 'Cancellable' protocol;
- If URLSessionDataTask conforms to 'Cancellable' protocol, why does not it implement the methods that 'Cancellable' protocol requires;
- When I check the initialiser of AnyCancellable, there is no initialiser which accepts an argument, so what does 'AnyCancellable(task)' do here and is it correct?
Appreciate any help.