Junior — Middle
How did you implement the Dependency Injection mechanism in your projects?
sobes.tech AI
Answer from AI
In my iOS projects, I have implemented Dependency Injection (DI) to improve code modularity and testability. I usually used constructor injection, where dependencies are passed through the class initializer. For example, if I have a ViewModel class that depends on an APIService, I pass this service via the initializer:
class APIService {
func fetchData() { /* ... */ }
}
class ViewModel {
private let apiService: APIService
init(apiService: APIService) {
self.apiService = apiService
}
func loadData() {
apiService.fetchData()
}
}
// Usage
let service = APIService()
let viewModel = ViewModel(apiService: service)
I also used Property Injection, where dependencies are set through properties, and sometimes employed a Service Locator for centralized dependency management, but I tried to avoid it due to testing difficulties. In large projects, I used DI containers, such as Swinject, for automatic dependency resolution.