Skip to content

Commit 1feae19

Browse files
committed
Update EnvironmentKey documentation
1 parent e7aa40a commit 1feae19

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Sources/OpenSwiftUICore/Data/Environment/EnvironmentKey.swift

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,20 @@ public protocol EnvironmentKey {
7070
/// The default value for the environment key.
7171
static var defaultValue: Value { get }
7272

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.
7387
static func _valuesEqual(_ lhs: Self.Value, _ rhs: Self.Value) -> Bool
7488
}
7589

@@ -85,7 +99,42 @@ extension EnvironmentKey where Value: Equatable {
8599
}
86100
}
87101

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+
///
88130
package protocol DerivedEnvironmentKey {
131+
/// The associated type representing the type of the environment key's
132+
/// value.
89133
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.
90139
static func value(in: EnvironmentValues) -> Value
91140
}

0 commit comments

Comments
 (0)