There are @State
, @ObservedObject
and @EnvironmentObject
bindings in SwfitUI
to share data between views and other objects. Each has its designated usage but @EnvironmentObject
seems to be the most powerful and easiest to use. So, can I use it for all state variables and shared data? Are there any downsides to this?
Asked
Active
Viewed 560 times
0
1 Answers
0
First, @EnvironmentObject
is for classes. So if you want to bind primitive type like Int - you can only use Binding
.
Second, I think it will couse a problems when you try to define more then one @EnvironmentObject
of same type. So, when you can use Binding
- you should do that. Thats only my appinion.
class SomeClass: ObservableObject{
@Published var value: Int
init(value: Int){
self.value = value
}
}
struct ContentView: View {
@State var one: SomeClass = SomeClass(value: 1)
@State var two: SomeClass = SomeClass(value: 2)
var body: some View {
Adss().environmentObject(one).environmentObject(two)
}
}
struct Adss: View{
@EnvironmentObject var two: SomeClass
var body: some View{
Text("there must be two: \(two.value)")//prints "1"
}
}
you will have to define all the objects of needed type in straight order even if you don't need them

Aspid
- 629
- 6
- 20