Sobes.tech
Junior — Middle

How is data passed to child components within a hierarchy in SwiftUI?

sobes.tech AI

Answer from AI

In SwiftUI, data passing to child components is usually done through properties passed to the initializer of the child View. This can be a simple value or a binding if the child component needs to modify the data.

Example of passing a value:

struct ParentView: View {
    let title = "Hello, SwiftUI!"

    var body: some View {
        ChildView(text: title)
    }
}

struct ChildView: View {
    let text: String

    var body: some View {
        Text(text)
    }
}

If you want the child component to be able to modify the data, you use @Binding:

struct ParentView: View {
    @State private var isOn = false

    var body: some View {
        ToggleView(isOn: $isOn)
    }
}

struct ToggleView: View {
    @Binding var isOn: Bool

    var body: some View {
        Toggle("Enable", isOn: $isOn)
    }
}

Thus, data is passed down through parameters, and changes can be passed back via bindings.

How is data passed to child components within a… - sobes.tech