Skip to content

Instantly share code, notes, and snippets.

@Wouter01
Created August 16, 2023 21:05
Show Gist options
  • Save Wouter01/4e22c9e8a30bc2b9c182e8dff7b84f70 to your computer and use it in GitHub Desktop.
Save Wouter01/4e22c9e8a30bc2b9c182e8dff7b84f70 to your computer and use it in GitHub Desktop.
SwiftUI EnvironmentObservable
import SwiftUI
import Observation
@propertyWrapper
struct EnvironmentObservable<Value: AnyObject & Observable>: DynamicProperty {
@Environment var wrappedValue: Value
public init(_ objectType: Value.Type) {
_wrappedValue = .init(objectType)
}
public init() {
_wrappedValue = .init(Value.self)
}
private var store: Bindable<Value>!
var projectedValue: Bindable<Value> {
store
}
mutating func update() {
store = Bindable(wrappedValue)
}
}
@Observable
class Model {
var someField = "Hello"
}
struct ContentView: View {
@EnvironmentObservable var model: Model
var body: some View {
VStack {
Text(model.someField.uppercased())
TextField("", text: $model.someField)
}
.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment