Dependency Injection in Swift 5
iOS developers have been using Dependency Injection (DI) for years. It’s a technique for decoupling components in an iOS app by injecting them with the services they need, rather than hard-coding those dependencies. This allows for more modular, testable code.
Swift 5 introduces new property wrappers that make DI even easier. Property wrappers are pieces of code that add functionality to properties, without the need for subclassing or custom accessors. In the case of DI, property wrappers can be used to inject dependencies into properties, without having to write any extra code. For example, consider the following view controller:
class MyViewController: UIViewController {
@Injected var userService: UserService
@Injected var name: String
…
}
In this code, the userService
property is injected with a user service dependency, and the name property is injected with a string value. Notice that neither of these properties is initialized explicitly; instead, they are simply marked with the @Injected attribute. When the view controller is instantiated, the iOS runtime will automatically inject the dependencies into these properties. This makes it easy to write loosely coupled code without having to worry about passing parameters around manually.