I have a binding of an array and I'm not sure what to put in the placeholder when calling the struct. I tried googling for solutions but i couldn't find anything helpful. If theres any more information i can add tell me and i can edit this.
You can usually get Binding
s via projected values ($
-prefixed variables). As an example, @State
wrapper properties have a Binding
as their projected value:
struct Foo {
@State var bar = ["swift", "rocks"]
}
let foo = Foo()
foo.$bar // is Binding<[String]>
Doing that now gives me this error
Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update.
Could you post the code (or a minimized version of it)?
struct GameView: View {
@Binding var usedLetters: [String]
var body: some View {
...
}
}
struct LettersView: View {
@State var usedLetters = [String]()
var body: some View {
...
}
}
struct ContentView: View {
let lettersView = LettersView()
var body: some View {
GameView(usedLetters: lettersView.$usedLetters) //error here
}
}
Generally, you can't reach into a view and get its state out. @State
values can only be used within the body of the view they're attached to. If both GameView and LettersView need access to the same property, then it should be an @State
in ContentView
and ContentView
should pass bindings down to both children.
struct GameView: View {
@Binding var usedLetters: [String]
var body: some View {
...
}
}
struct LettersView: View {
@Binding var usedLetters: [String]
var body: some View {
...
}
}
struct ContentView: View {
@State var usedLetters = [String]()
var body: some View {
GameView(usedLetters: $usedLetters)
// .. somewhere leter
LettersView(usedLetters: $usedLetters)
}
}
SwiftUI much prefers data dependencies to flow downwards -- if two siblings need access to the same data, then a parent should own it.
Thank you so much, that has fixed it
This is exactly why Apple tells you to mark State
properties as private. You should do this.