SwiftEnvironment is a Swift library designed to allow global access to SwiftUI EnvironmentValues.
- Swift 5.9 or higher
- iOS 15.0 or higher
- MacOS 12.0 or higher
- TVOS 15.0 or higher
- WatchOS 8.0 or higher
- VisionOS 1.0 or higher
- Xcode 15 or higher
To install using Xcode's Swift Package Manager, follow these steps:
- Go to File > Swift Package > Add Package Dependency
- Enter the URL: https://github.com/hainayanda/SwiftEnvironment.git
- Choose Up to Next Major for the version rule and set the version to 3.0.1.
- Click "Next" and wait for the package to be fetched.
If you prefer using Package.swift, add SwiftEnvironment as a dependency in your Package.swift file:
dependencies: [
.package(url: "https://github.com/hainayanda/SwiftEnvironment.git", .upToNextMajor(from: "3.0.1"))
]
Then, include it in your target:
.target(
name: "MyModule",
dependencies: ["SwiftEnvironment"]
)
This library allows you to utilize EnvironmentValues
as global managed Environment:
// provide environment as usual
extension EnvironmentValues {
@Entry var myValue: SomeDependency = SomeDependency()
}
// assign real dependency so it can be accessed globally
EnvironmentValue.global
.environment(\.myValue, SomeDependency(id: "real-dependency"))
Then you can access the value from anywhere globally:
@GlobalEnvironment(\.myValue) var myValue
or inject it to SwiftUI Environment by using @EnvironmentSource
:
@main
struct MyApp: App {
@EnvironmentSource(.global) var source
var body: some Scene {
WindowGroup {
ContentView()
}
.defaultEnvironment(\.myValue, from: source)
}
}
or from SwiftUI environment:
@main
struct MyApp: App {
@EnvironmentSource(.global) var source
var body: some Scene {
WindowGroup {
ContentView()
}
.environment(\.myValue, MyValue(), injectTo: source)
}
}
Both @GlobalEnvironment
and @EnvironmentSource
will be updated when the value is updated from EnvironmentValue.global
and if used inside SwiftUI View will trigger SwiftUI render event if needed.
Another injection method for GlobalResolver is transient
. This method ensures that the value will be newly created when first accessed from GlobalEnvironment property wrapper. To inject, simply call transient from GlobalEnvironment and proceed as usual:
EnvironmentValue.global
.transient(\.myValue, SomeDependency())
Another injection method for GlobalResolver is weak
. This method ensures that the value will be stored in a weak variable and will be newly created only when the last resolved value is null. To inject, simply call weak from GlobalEnvironment and proceed as usual:
EnvironmentValue.global
.weak(\.myValue, SomeDependency())
Contributions are welcome! Please follow the guidelines in the CONTRIBUTING.md file.
MosaicGrid is available under the MIT license. See the LICENSE file for more info.
This project is maintained by Nayanda Haberty.