SwiftUI @State vs @Binding vs @Bindable in ParentView and ChildView

i use @Observable

@Observable
class TextClass {
    var text: String = ""
}

@State

struct ContentView: View {
    @State var text: TextClass = .init()
    var body: some View {
        Form {
            Text(text.text)
            Button("upup") {
                text.text += "1"
            }
        }
        Form {
            ChildView(text: text)
        }
    }
}

struct ChildView: View {

    @State var text: TextClass

    var body: some View {
        Text (text.text)
        Button("upup Child") {
            text.text += "2"
        }
    }
}

@Binding

struct ContentView: View {
    @State var text: TextClass = .init()
    var body: some View {
        Form {
            Text(text.text)
            Button("upup") {
                text.text += "1"
            }
        }
        Form {
            ChildView(text: $text)
        }
    }
}

struct ChildView: View {

    @Binding var text: TextClass

    var body: some View {
        Text (text.text)
        Button("upup Child") {
            text.text += "2"
        }
    }
}

@Bindable


struct ContentView: View {
    @State var text: TextClass = .init()
    var body: some View {
        Form {
            Text(text.text)
            Button("upup") {
                text.text += "1"
            }
        }
        Form {
            ChildView(text: text)
        }
    }
}

struct ChildView: View {

    @Bindable var text: TextClass

    var body: some View {
        Text (text.text)
        Button("upup Child") {
            text.text += "2"
        }
    }
}

What are the differences between @State, @Binding, and @Bindable, all of which function similarly for bidirectional binding? Which one should I use?

I'm curious about the differences between the three.

What are the differences between @State, @Binding

They both refer to state var in the View.

But @State var "belongs" to the view

@Binding var "belongs" to another view, that means there is another State var in the other view that share the same pointer. So when you change var in the other view, it is also changed in the first.

There are many tutorials to explain, like these ones:

  • https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-binding-property-wrapper
  • https://www.hackingwithswift.com/quick-start/swiftdata/whats-the-difference-between-bindable-and-binding
SwiftUI @State vs @Binding vs @Bindable in ParentView and ChildView
 
 
Q