Dependency icon indicating copy to clipboard operation
Dependency copied to clipboard

A dependency Injection solution for SwiftUI. Thank you Antoine van der Lee and Vincent Pradeilles for initially showcasing this idea.

Dependency

A dependency Injection solution for SwiftUI. Thank you Antoine van der Lee and Vincent Pradeilles for initially showcasing this idea.

Usage

Register a Service as a Dependency

private struct UserServiceKey: DependencyKey {
    static var currentValue: UserService = MyUserService()
}

extension DependencyValues {
    var userService: UserService {
        get { Self[UserServiceKey.self] }
        set { Self[UserServiceKey.self] = newValue }
    }
}

Access a Service, e.g. inside a ViewModel

@Dependency(\.userService) private var userService

Set a Service, e.g. inside a Unit Test

DependencyValues[\.userService] = MockUserService()