Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ struct GreetingGeneratorApp: App {

Toggle("Selectable Greeting", active: $isGreetingSelectable)
if let latest = greetings.last {
Text(latest)
LatestGreetingDisplay()
.environment(\.latestGreeting, latest)
.padding(.top, 5)
.textSelectionEnabled(isGreetingSelectable)

Expand All @@ -51,3 +52,24 @@ struct GreetingGeneratorApp: App {
}
}
}

/// This intermediate view exists to show the usage of custom environment keys. In reality it is not necessary.
struct LatestGreetingDisplay: View {
@Environment(\.latestGreeting) var value: String?

var body: some View {
Text(value ?? "nil")
}
}

struct LatestGreetingKey: EnvironmentKey {
typealias Value = String?
static let defaultValue: Value = nil
}

extension EnvironmentValues {
var latestGreeting: String? {
get { self[LatestGreetingKey.self] }
set { self[LatestGreetingKey.self] = newValue }
}
}
2 changes: 1 addition & 1 deletion Sources/SwiftCrossUI/Environment/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public struct Environment<Value>: DynamicProperty {
guard let value = value.value else {
fatalError(
"""
Environment value \(keyPath) used before initialization. Don't \
Environment value at \(keyPath) used before initialization. Don't \
use @Environment properties before SwiftCrossUI requests the \
view's body.
"""
Expand Down
2 changes: 1 addition & 1 deletion Sources/SwiftCrossUI/Environment/EnvironmentValues.swift
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ public struct EnvironmentValues {
}

/// A key that can be used to extend the environment with new properties.
public protocol EnvironmentKey {
public protocol EnvironmentKey<Value> {
/// The type of value the key can hold.
associatedtype Value
/// The default value for the key.
Expand Down
11 changes: 11 additions & 0 deletions Sources/SwiftCrossUI/Views/Modifiers/EnvironmentModifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,14 @@ package struct EnvironmentModifier<Child: View>: View {
)
}
}

extension View {
/// Modifies the environment of the View its applied to
public func environment<T>(_ keyPath: WritableKeyPath<EnvironmentValues, T>, _ newValue: T)
-> some View
{
EnvironmentModifier(self) { environment in
environment.with(keyPath, newValue)
}
}
}
Loading