EnvironmentObject to Binding

Hello,

how do I convert an EnvironmentObject to a Binding?
In my GameView have have:

GameView.swift
Code Block
struct GameView: View {
@EnvironmentObject private var game: ObserveableGame
var body: some View {
...
.sheet(isPresented: $addingPoints) {
AddPointsView(game: $game)
}
}
}


and my AddPointsView:

Code Block
struct AddPointsView: View {
@Binding var game: ObserveableGame
var body: some View {
...
}
}


But in the GameView.swift I get an error on the (translated) line 6:

Cannot convert value of type 'EnvironmentObject<ObserveableGame>.Wrapper' to expected argument type 'Binding<ObserveableGame>'

How do I make a binding to an EnviromentObject?

Answered by Developer Tools Engineer in 617513022
You don’t. An @Binding is mutable (you could set AddPointsView.game to a different value) but @EnvironmentObject is not mutable (you can set the properties of GameView.game, but you can’t replace the entire GameView.game object with a different one). So you can get bindings to GameView.game’s properties through GameView.$game, but you can’t get a binding to GameView.game itself.

Consider separating ObservableGame into a struct which contains your game data and a class which manages a property of the struct’s type. Then you’ll be able to take a binding of your game data struct and pass it to the child. Alternatively, consider using @ObservedObject on AddPointsView.game, rather than Binding.
Accepted Answer
You don’t. An @Binding is mutable (you could set AddPointsView.game to a different value) but @EnvironmentObject is not mutable (you can set the properties of GameView.game, but you can’t replace the entire GameView.game object with a different one). So you can get bindings to GameView.game’s properties through GameView.$game, but you can’t get a binding to GameView.game itself.

Consider separating ObservableGame into a struct which contains your game data and a class which manages a property of the struct’s type. Then you’ll be able to take a binding of your game data struct and pass it to the child. Alternatively, consider using @ObservedObject on AddPointsView.game, rather than Binding.
EnvironmentObject to Binding
 
 
Q