Junior — Middle
Explain the concept of dependency injection and how it is applied in programming.
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a design pattern where an object receives its dependencies from outside rather than creating them itself. This increases modularity, simplifies testing, and improves code maintenance.
In iOS programming, DI is often implemented by passing dependencies through the class constructor or via properties. For example, if you have a ViewController class that depends on a NetworkService, you can pass this service in the initializer:
class NetworkService {
func fetchData() { /* ... */ }
}
class ViewController {
let networkService: NetworkService
init(networkService: NetworkService) {
self.networkService = networkService
}
func loadData() {
networkService.fetchData()
}
}
// Usage:
let service = NetworkService()
let vc = ViewController(networkService: service)
This approach makes it easy to replace NetworkService with a mock object during testing, and also improves code readability and maintainability.