0Pricing
Swift Academy · Lesson

Dependency Inversion with Protocol Abstractions

Depending on abstractions not concretions using Swift protocols as boundaries.

Dependency Inversion Principle

High-level modules should not depend on low-level modules. Both should depend on abstractions (protocols).

// WITHOUT DIP:
class OrderService { let db = SQLiteDatabase() }  // depends on concrete
// WITH DIP:
class OrderService { let db: Database }  // depends on abstraction

Defining the Abstraction

Extract a protocol that captures the contract your high-level module needs.

protocol Database {
  func save<T: Encodable>(_ value: T, key: String) throws
  func load<T: Decodable>(key: String) throws -> T
}

All lessons in this course

  1. Layers: Domain, Data and Presentation
  2. Use Case and Repository Patterns
  3. Dependency Inversion with Protocol Abstractions
  4. Wiring Layers Together without a DI Framework
← Back to Swift Academy