I am trying to create a subclass of URLSession
in Swift (reason does not matter, but has to do with testing). I need it to work with a delegate
and a specific URLSessionConfiguration
, which is a read-only property on URLSession
. Usual way to initialize URLSession
with delegate is done with the code below, which works flawlessly:
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
Now lets create a subclass:
class MyURLSession : URLSession {}
let session = MyURLSession(configuration:
URLSessionConfiguration.default, delegate: nil, delegateQueue: nil) // Compile error
The initializer triggers next compile error:
error: argument passed to call that takes no arguments
According to Swift Language Guide rule 1 for Automatic Initializer Inheritance:
If your subclass doesn’t define any designated initializers, it
automatically inherits all of its superclass designated initializers.
So, technically MyURLSession
should inherit all designated initializers, but it doesn't, and it only inherits init()
from NSObject
. Looking into documentation of URLSession
:
public /*not inherited*/ init(configuration: URLSessionConfiguration)
public /*not inherited*/ init(configuration: URLSessionConfiguration, delegate: URLSessionDelegate?, delegateQueue queue: OperationQueue?)
There is nothing visible aside from the comment, that it is not inherited. Looking into it's Objective-C definitions, we can notice that they are not initializers, but rather factory methods, which are imported into Swift as inits.
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(nullable id <NSURLSessionDelegate>)delegate delegateQueue:(nullable NSOperationQueue *)queue;
So the question is, how to override and/or correctly call these methods of superclass in initialization?
URLSession
and I am aware how to test using mocks. This question remains, if it is generic: on how to override compiler generated initializers from factory methods,URLSession
was merely an example. – Apprehensive