Decoupling with Dependency Injection
DI is a powerful pattern that helps us to create modular and testable code. It’s another tool in our toolbox that can help us make our code flexible and decoupled.
There are several ways to implement DI in iOS, which are discussed next.
Using constructor injection
This is the most common form of DI in iOS. In constructor injection, dependencies are passed into an object through its initializer. For example, if we have a view controller that depends on a data manager, we can inject the data manager into the view controller’s initializer.
In the following code example, we created a custom init()
function and a private variable to hold the injected data manager:
class MyViewController: UIViewController { private let dataManager: DataManager init(dataManager: DataManager) { self.dataManager = dataManager ...