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:
- 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 4.1.4
- Click "Next" and wait for the package to be fetched
To add SwiftEnvironment as a dependency in your Package.swift file:
dependencies: [
.package(url: "https://github.com/hainayanda/SwiftEnvironment.git", .upToNextMajor(from: "4.1.4"))
]
Then include it in your target:
.target(
name: "MyModule",
dependencies: ["SwiftEnvironment"]
)
Define your global values using the @GlobalEntry
macro:
extension GlobalValues {
@GlobalEntry var myValue: SomeDependency = SomeDependency()
}
Access global values directly:
let value = GlobalValue.myValue
Or use property wrappers in SwiftUI views:
@GlobalEnvironment(\.myValue) var myValue
The @GlobalEnvironment
property wrapper implements DynamicProperty
, ensuring your view automatically updates whenever the source value changes, similar to SwiftUI's @Environment
:
struct MyView: View {
@GlobalEnvironment(\.myValue) var myValue
var body: some View {
Text(myValue.description)
}
}
There are several ways to set and manage global values:
Set a value directly:
GlobalValues.environment(\.myValue, SomeNewValue())
Create values that are always newly instantiated on access:
GlobalValues.transient(\.myValue, SomeNewValue())
Create values that can be deallocated when no longer referenced:
GlobalValues.weak(\.myValue, SomeNewValue())
You can provide a closure for value creation (all value setters use autoclosure under the hood):
GlobalValues.environment(\.myValue) {
SomeNewValue()
}
Specify which DispatchQueue should handle value access:
GlobalValues.environment(\.myValue, resolveOn: .main, SomeNewValue())
Note: Queue specification is available for all value types (environment, transient, and weak).
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
SwiftEnvironment is available under the MIT license. See the LICENSE file for more info.
Maintained by Nayanda Haberty