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:
Appreciate any help.
- What is the purpose of making URLSessionDataTask conform to 'Cancellable' protocol?
So that you could use AnyCancellable
. AnyCancellable
initializer only works with types conforming to Cancellable
.
- If URLSessionDataTask conforms to 'Cancellable' protocol, why does not it implement the methods that 'Cancellable' protocol requires;
Cancallable
requires there to be a method cancel
and store(in:)
. cancel
already exists on URLSessionTask
- a base class of URLSessionDataTask
, and store(in:)
is implemented as an extension on Cancellable
providing a default implementation.
- 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?
AnyCancellable
has init(_:)
that accepts a Cancellable