1
votes

Goal: To simply pass struct per List row to a secondary View via NavigationLink.

Baby Step (prior goal): Merely pass a member of a String Array to the secondary view.

Problem: The Secondary View is expecting a Binding-String value in the parameter call vs the closure String value within the context.

So I have to set the @State var to the current/context value prior to the call.

That's my problem. I can't simply equate the Binding var with the current context var; because in SwiftUI, such statements are limited to View based stuff only.

This doesn't work:

enter image description here

Here's the actual code:

import SwiftUI
  
struct ContentView: View {
    @State var name = ""   //... load with inital value to avoid having to add a call parameter.
    
    var body: some View {
        let myArray = ["Larry", "Moe", "Curly"]
        NavigationView {
            List(myArray, id: \.self) { theStooge in
                NavigationLink(destination: SecondView(stoogeName: theStooge)) {
                    Text(theStooge)
                }
            }
            .navigationBarTitle("Three Stooges").navigationBarTitleDisplayMode(.inline)
        }
    }
}

struct SecondView: View {
    @Binding var stoogeName: String
    var body: some View {
        Text("Hello \(name)")
    }
}

I can merely create the SecondView via a Text("Hello World") in the NavigationLink's destination parameter. But that's not very helpful. I want to pass data (struct of data) to a secondary View per List member.

But I need to set a binding variable. How?
Do I have to jury rig an EnvironmentObject or Singleton?

1

1 Answers

1
votes

Binding can be set to dynamic property but your array is constant local variable. Here is possible solution to work with binding:

struct ContentView: View {
    @State var name = ""   //... load with inital value to avoid having to add a call parameter.
    
    @State private var myArray = ["Larry", "Moe", "Curly"]

    var body: some View {
        NavigationView {
            List(myArray.indices, id: \.self) { index in
                NavigationLink(destination: SecondView(stoogeName: $myArray[index])) {
                    Text(myArray[index])
                }
            }
            .navigationBarTitle("Three Stooges").navigationBarTitleDisplayMode(.inline)
        }
    }
}