"Does not conform to protocol" error when extending different class

742 Views Asked by At

I'm attempting to test my own class by injecting objects that adapt the URLSession and URLSessionDataTask protocols. I'm extending NSURLSession and NSURLSessionDataTask to adopt those protocols so that I can use the existing objects normally, but use test objects in unit tests.

I have the following code, with the error commented:

typealias SessionHandler = (NSData?, NSURLResponse?, NSError?) -> Void

protocol URLSession {

  func dataTaskWithURL(url: NSURL, completionHandler: SessionHandler) -> URLSessionDataTask

}

protocol URLSessionDataTask {

}

// Type 'NSURLSession' does not conform to protocol 'URLSession'
extension NSURLSession : URLSession {}
extension NSURLSessionDataTask : URLSessionDataTask {}

I understand the error, my protocol doesn't exactly match the method as implimented by NSURLSession. How do I fix this?

1

There are 1 best solutions below

0
On

What I ended up doing was creating a protocol extension that creates the necessary method that NSURLSession requires.

extension NSURLSession : URLSession {
  func dataTaskWithURL(url: NSURL, completionHandler: SessionHandler) -> URLSessionDataTask {
    return dataTaskWithURL(url, completionHandler: completionHandler) as NSURLSessionDataTask
  }
}