What are dependency injection approaches for URLSession in Swift?

In Swift, dependency injection for `URLSession` can be achieved through various approaches, enhancing testability and flexibility in your applications. Here are a few common methods:

  • Initializer Injection: Pass an instance of `URLSession` via the initializer of a class or struct.
  • Property Injection: Assign an instance of `URLSession` to a property after the object has been initialized.
  • Method Injection: Pass `URLSession` as a parameter to methods that require it.

Below is an example demonstrating initializer injection:

class NetworkManager { let session: URLSession init(session: URLSession = .shared) { self.session = session } func fetchData(from url: URL, completion: @escaping (Data?) -> Void) { let task = session.dataTask(with: url) { data, response, error in guard error == nil else { completion(nil) return } completion(data) } task.resume() } } // Usage let mySession = URLSession(configuration: .default) let networkManager = NetworkManager(session: mySession) // Call fetchData with a valid URL

dependency injection URLSession Swift initializer injection property injection method injection