How do I design for dependency injection with URLSession in Swift?

Designing for dependency injection with URLSession in Swift allows developers to create more testable and flexible code. By injecting URLSession into your classes or functions, you can easily mock network calls in unit tests. Below is an example illustrating how to implement dependency injection with URLSession:

// Define a protocol for the network layer protocol NetworkService { func fetchData(from url: URL, completion: @escaping (Data?, Error?) -> Void) } // Create a concrete implementation of the protocol class URLSessionNetworkService: NetworkService { private let session: URLSession init(session: URLSession = .shared) { self.session = session } func fetchData(from url: URL, completion: @escaping (Data?, Error?) -> Void) { let task = session.dataTask(with: url) { data, response, error in completion(data, error) } task.resume() } } // Use dependency injection in your view model or other classes class ViewModel { private let networkService: NetworkService init(networkService: NetworkService) { self.networkService = networkService } func loadData(from url: URL) { networkService.fetchData(from: url) { data, error in // Handle the response } } }

Swift Dependency Injection URLSession Networking Testable Code Swift Protocols