Junior — Middle
How would you implement your own Dependency Injection mechanism for managing dependencies in an application?
sobes.tech AI
Answer from AI
To implement your own Dependency Injection (DI) mechanism in an iOS app, you can create a simple container that stores dependencies and provides them upon request.
Example in Swift:
// Protocol for a service
protocol ApiService {
func fetchData()
}
// Concrete implementation
class ApiServiceImpl: ApiService {
func fetchData() {
print("Data loaded")
}
}
// DI container
class DIContainer {
static let shared = DIContainer()
private var services = [String: Any]()
func register<T>(_ service: T) {
let key = String(describing: T.self)
services[key] = service
}
func resolve<T>() -> T? {
let key = String(describing: T.self)
return services[key] as? T
}
}
// Usage
let container = DIContainer.shared
container.register(ApiServiceImpl() as ApiService)
if let apiService: ApiService = container.resolve() {
apiService.fetchData()
}
This approach allows centralized management of dependencies, simplifies testing, and increases code modularity.