Sobes.tech
Junior — Middle

What is the main goal of implementing Dependency Injection in a project?

sobes.tech AI

Answer from AI

The main goal of Dependency Injection (DI) in a project is to increase modularity, testability, and flexibility of the code. DI allows separating the creation of dependencies from their use, making it easier to replace components without changing the code that uses them.

In iOS development, this helps to:

  • Simplify writing unit tests by substituting mocks instead of real dependencies.
  • Improve application architecture by making components less coupled.
  • Facilitate maintenance and extension of the code.

A simple example of DI in Swift:

protocol NetworkService {
    func fetchData()
}

class RealNetworkService: NetworkService {
    func fetchData() {
        // Implementation
    }
}

class ViewModel {
    private let networkService: NetworkService

    init(networkService: NetworkService) {
        self.networkService = networkService
    }

    func loadData() {
        networkService.fetchData()
    }
}

// Injecting dependency
let service = RealNetworkService()
let viewModel = ViewModel(networkService: service)