@@ -70,6 +70,20 @@ public protocol EnvironmentKey {
70
70
/// The default value for the environment key.
71
71
static var defaultValue : Value { get }
72
72
73
+ /// Compares two values of the environment key's associated type.
74
+ ///
75
+ /// This function determines if two values of this environment key's
76
+ /// associated type should be considered equal. OpenSwiftUI uses this
77
+ /// to determine when environment changes should trigger view updates.
78
+ ///
79
+ /// - Parameters:
80
+ /// - lhs: The first value to compare.
81
+ /// - rhs: The second value to compare.
82
+ /// - Returns: `true` if the values are considered equal; otherwise, `false`.
83
+ ///
84
+ /// The default implementation uses general value comparison for non-Equatable types.
85
+ /// Types conforming to `Equatable` receive an optimized implementation that uses
86
+ /// the `==` operator.
73
87
static func _valuesEqual( _ lhs: Self . Value , _ rhs: Self . Value ) -> Bool
74
88
}
75
89
@@ -85,7 +99,42 @@ extension EnvironmentKey where Value: Equatable {
85
99
}
86
100
}
87
101
102
+ /// A protocol that defines environment keys derived from other environment values.
103
+ ///
104
+ /// Unlike standard `EnvironmentKey` that stores values directly, a `DerivedEnvironmentKey`
105
+ /// calculates its value dynamically based on other environment values.
106
+ ///
107
+ /// To implement a derived environment key:
108
+ /// 1. Create a type that conforms to `DerivedEnvironmentKey`
109
+ /// 2. Specify the `Value` type that must conform to `Equatable`
110
+ /// 3. Implement the `value(in:)` method to compute the derived value
111
+ ///
112
+ /// Example:
113
+ ///
114
+ /// private struct MyDerivedKey: DerivedEnvironmentKey {
115
+ /// typealias Value = String
116
+ ///
117
+ /// static func value(in values: EnvironmentValues) -> String {
118
+ /// return "\(values.someOtherValue) derived"
119
+ /// }
120
+ /// }
121
+ ///
122
+ /// Then extend `EnvironmentValues` to access your derived value:
123
+ ///
124
+ /// extension EnvironmentValues {
125
+ /// var myDerivedValue: String {
126
+ /// self[MyDerivedKey.self]
127
+ /// }
128
+ /// }
129
+ ///
88
130
package protocol DerivedEnvironmentKey {
131
+ /// The associated type representing the type of the environment key's
132
+ /// value.
89
133
associatedtype Value : Equatable
134
+
135
+ /// Calculates the derived value based on the current environment values.
136
+ ///
137
+ /// - Parameter values: The current environment values.
138
+ /// - Returns: The derived value for this key.
90
139
static func value( in: EnvironmentValues ) -> Value
91
140
}
0 commit comments