Skip to content

Latest commit

 

History

History
66 lines (39 loc) · 1.93 KB

README.md

File metadata and controls

66 lines (39 loc) · 1.93 KB

Dependencies

License Language Coverage

A lightweight library implementing functionality similar to @Environment from SwiftUI but allowing to be used in any Swift class or struct.

Installation

Swift Package Manager

Add "Dependencies" dependency via integrated Swift Package Manager in XCode

Usage

To register global dependency statically, you first need to create custom dependency value by extending the DependencyValues structure with new properties. Declare a new dependency key type and specify a value for the required defaultValue property:

    private struct MyDependencyKey: DependencyKey {
        static let defaultValue: String = "Default value"
    }
    

The Swift compiler automatically infers the associated Value type as the type you specify for the default value.

Then use the key to define a new dependency property:

    extension Dependencies {
        var myCustomValue: String {
            get { self[MyDependencyKey.self] }
            set { self[MyDependencyKey.self] = newValue }
        }
    }

To access the dependency, declare a property using the Dependency property wrapper and specify the value's key path:

@Dependency(\.myCustomValue) 
var customValue: String

To register dependency dynamically without registering new DependencyKey, call Dependencies instance method register and pass the object:

Dependencies.default.register(instance: MyCustomObject())
    

To access dynamically registered dependency instance, use Dependency property wrapper passing the type of the object and optional container, or just omit any parameters:

@Dependency 
var customObject: MyCustomObject