Swiftpack.co - kzlekk/Dependencies as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
kzlekk/Dependencies
A lightweight library replicating @Environment from SwiftUI but allowing to be used in any Swift class or struct.
.package(url: "https://github.com/kzlekk/Dependencies.git", from: "1.0.1")

Dependencies

License Language Coverage

A lightweight library replicating @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
    

GitHub

link
Stars: 0
Last commit: 5 days ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Submit a free job ad (while I'm testing this). The analytics numbers for this website are here.

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics