Skip to content

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

License

Notifications You must be signed in to change notification settings

CozmoNate/Dependencies

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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
    

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages