0Pricing
Swift Academy · Lesson

Why Dependency Injection

Separate construction from use for testability.

Why Dependency Injection

Dependency injection (DI) means giving an object the things it needs from outside, instead of letting it create them itself. This decouples components and makes them easier to test.

The Problem: Hard Coupling

When a type constructs its own collaborators, it is locked to those concrete classes and cannot be reconfigured or tested in isolation.

class Logger {
    func log(_ m: String) { print("LOG: \(m)") }
}
class Service {
    let logger = Logger() // hard-coded dependency
    func run() { logger.log("running") }
}
Service().run()

All lessons in this course

  1. Why Dependency Injection
  2. Constructor Injection
  3. Protocol-Based Abstractions
  4. Mocking Dependencies in Tests
← Back to Swift Academy