Property type 'Int' does not match that of the 'wrappedValue' property of its wrapper type 'EnvironmentObject'
@EnvironmentObject
can only be used with a class
. Int
is actually a struct
.
Also, it should look more like this inside SceneDelegate.swift
:
let contentView = ContentView().environmentObject(SharedInt())
if let windowScene = /* ... */
If you did want to try to share that Int
between View
s, you could wrap the value in a class:
class SharedInt: ObservableObject {
@Published var myInt = 1
}
If you want to use the environment system, you need to provide a key to access it. You can't use an unregistered key (which is what your error is). First, create an EnvironmentKey
:
struct MyIntEnvironmentKey: EnvironmentKey {
static var defaultValue = 0
}
Next, create a key path to set/get your environment value:
extension EnvironmentValues {
var myInt: Int {
get { self[MyIntEnvironmentKey.self] }
set { self[MyIntEnvironmentKey.self] = newValue }
}
}
Now, you can set it in your parent View:
MyView().environment(\.myInt, myInt)
And crucially, you need to reference the key in the view in which you want to reference it:
struct MyView: View {
@Environment(\.myInt) private var myInt: Int
var body: some View {
Text("\(self.myInt)")
}
}