Skip to content

Instantly share code, notes, and snippets.

@johnhammerlund
Created February 2, 2019 19:40
Show Gist options
  • Save johnhammerlund/b6e135a356fedafe01073f30e89de282 to your computer and use it in GitHub Desktop.
Save johnhammerlund/b6e135a356fedafe01073f30e89de282 to your computer and use it in GitHub Desktop.
Swift Dependency Injection - ELI5
/// ❌ Without dependency injection
public final class Kid {
private let fridge = Refridgerator()
func eatLunch() {
let food = fridge.fetchFood()
let drink = fridge.fetchDrink() /// POTENTIAL ERROR: Might be expired!
consume([food, drink])
}
private func consume(_ items: [Consumable]) {}
}
/// ✅ With dependency injection
protocol DrinkService {
func fetchDrink()
}
protocol FoodService {
func fetchFood()
}
public final class Kid {
private let foodService: FoodService
private let drinkService: DrinkService
init(foodService: FoodService, drinkService: DrinkService) {
self.foodService = foodService
self.drinkService = drinkService
}
func eatFood() {
/// Someone else will make sure you have something when you sit down to eat
let food = foodService.fetchFood()
let drink = drinkService.fetchDrink()
consume([food, drink])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment