I'm trying to use an @EnvironmentObject to pass data to my SwiftUI view:
struct MyView: View {
@EnvironmentObject var myInt: Int // ❌ Property type 'Int' does not match that of the 'wrappedValue' property of its wrapper type 'EnvironmentObject'
var body: some View {
EmptyView()
}
}
func constructView() {
let myInt = 1
MyView()
.environmentObject(myInt)
}
The line with @EnvironmentObject had a compiler error (listed above).
How do I use @EnvironmentObject
with an Int
?
Update: One thought was that @EnvironmentObject
can only be used with classes that conform to ObservableObject
, so I tried switching to @Environment
which now that part compiled, but produced a different error:
struct MyView: View {
@Environment var myInt: Int
var body: some View {
EmptyView()
}
}
func constructView() {
let myInt = 1
MyView() // ❌ Missing argument for parameter 'myInt' in call
.environment(\.myInt, myInt)
}
Now when I attempt to construct it, it complains that myInt
isn't set.