Pass data to a child component in SwiftUI

Hello, how can I pass data to a child component in SwiftUI? I want to pass a name to a child component but there is an error in the child component (I have uploaded an image which shows the error).

I have a parent component called Content_View:

struct ContentView: View {
    @State private var name = "Eric"
    var body: some View {
        ZStack {
            AnotherScreen(name: $name)
        }
        .padding()
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

and a child component called AnotherScreen.

struct AnotherScreen: View {
    @Binding public var name: String
    var body: some View {
        Text(name)
    }
}

struct AnotherScreen_Previews: PreviewProvider {
    static var previews: some View {
        AnotherScreen(name: String)
    }
}

When I change the type of name to Binding then there is an error: Cannot convert value of type 'Binding<String>.Type' to expected argument type 'Binding<String>'

Accepted Answer

That's not how you pass something to AnotherScreen(), or any other function.

AnotherScreen() has a String var called name. You need to pass in something for that var.

Your preview is going to send a name which is a String var into AnotherScreen(), so because it's a preview and you don't have name anywhere in the preview struct you would use something like this:

struct AnotherScreen_Previews: PreviewProvider {
    static var previews: some View {
        AnotherScreen("Dave")
    }
}

// or

struct AnotherScreen_Previews: PreviewProvider {
  let name: String = "Dave"
    static var previews: some View {
        AnotherScreen(name)
    }
}

For your actual usage, i.e. where you're passing through Eric, that should work fine as it is because you're passing through the name var: AnotherScreen(name: $name).

Pass data to a child component in SwiftUI
 
 
Q