Dependency Injection by example
After spending a few pages defining and explaining Dependency Injection and its principles, now let's see how to implement it in Swift.
Four ways to use Dependency Injection (with examples)
Dependency Injection is used ubiquitously in Cocoa too, and in the following examples, we'll see code snippets both from Cocoa and typical client-side code. Let's take a look at the following four sections to learn how to use Dependency Injection.
Constructor Injection
The first way to do DI is to pass the collaborators in the constructor, where they are then saved in private properties. Let's have as an example on e-commerce app, whose Basket is handled both locally and remotely.
The BasketClient
class orchestrates the logic, saves locally in BasketStore
, and synchronizes remotely with BasketService
:
protocol BasketStore { func loadAllProduct() -> [Product] func add(product: Product) func delete(product: Product) } protocol BasketService { func fetchAllProduct...