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
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?