iTranslated by AI
[SwiftUI] Adding Generic @Environment / EnvironmentValues
Introduction
One of the useful features in SwiftUI is @Environment. It is highly valued because it allows for easy passing of values between Views across different levels of the hierarchy.
@Environment has an initializer that takes a KeyPath<EnvironmentValues, T>, and is used like this, for example:
struct ContentView: View {
// Get the color scheme of the environment
@Environment(\.colorScheme) var colorScheme: ColorScheme
// Omitted
}
According to the documentation, you can add your own environment values to your codebase by extending EnvironmentValues.
struct UserEnvironmentKey: EnvironmentKey {
typealias Value = User
static var defaultValue: User = .default
}
extension EnvironmentValues {
var currentUser: User {
get {
self[UserEnvironmentKey.self]
}
set {
self[UserEnvironmentKey.self] = newValue
}
}
}
By doing this, you can retrieve the user just by writing @Environment(\.currentUser).
Making it Generic
It might be a rare situation, but you might want to make this @Environment generic. In other words, you want different environment values depending on the specified type.
// It would be great if it could be used like this
@Environment(\.user) var hogeUser: HogeUser
@Environment(\.user) var fugaUser: FugaUser
Now, let's implement this (or something close to it).
Defining User
Define a protocol for User and prepare two types of user models for now.
protocol UserProtocol {
static var `default`: Self { get }
}
struct HogeUser: UserProtocol {
static var `default`: Self { Self() }
}
struct FugaUser: UserProtocol {
static var `default`: Self { Self() }
}
Extending EnvironmentValues
This is similar to a regular extension, but the EnvironmentKey is generic and uses a subscript in the EnvironmentValues extension.
struct GenericUserEnvironmentKey<User: UserProtocol>: EnvironmentKey {
typealias Value = User
static var defaultValue: Value { User.default }
}
struct UserSpecifier<User: UserProtocol>: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(String(describing: User.self))
}
}
extension EnvironmentValues {
subscript<User: UserProtocol>(user _: UserSpecifier<User>) -> User {
get {
self[GenericUserEnvironmentKey<User>.self]
}
set {
self[GenericUserEnvironmentKey<User>.self] = newValue
}
}
}
I've added a mysterious type called UserSpecifier, which is a workaround for subsequent processing.
Adding an init to Environment
Define an init for Environment using the KeyPath to the subscript added earlier.
extension Environment {
init() where Value: UserProtocol {
self.init(\.[user: UserSpecifier()])
}
}
UserSpecifier is necessary to use the KeyPath in this way.
It might seem that Value.self would suffice if you only want to specify the type, but the arguments provided to a subscript in a KeyPath must be Hashable. Since metatypes are not Hashable, they cannot be used in this case. Therefore, UserSpecifier is used as a Hashable substitute for the metatype. Within it, the hash is calculated using the type's metadata, making it effectively treatable as Hashable.
Adding a modifier to View
Implement it as follows:
extension View {
func userEnvironment(_ value: some UserProtocol) -> some View {
self.environment(\.[user: UserSpecifier()], value)
}
}
Usage
It can be used like this.
struct ContentView: View {
@Environment private var hogeUser: HogeUser
@Environment private var fugaUser: FugaUser
// Omitted
}
Conclusion
I have implemented generic @Environment / EnvironmentValues.
The actual motivation was DI (Dependency Injection). I struggled to find a way to achieve polymorphism with @Environment even after passing injected types down to lower-level Views, and this is the method I eventually came up with. While its use cases might be limited, I hope it helps someone.
Discussion