Passing data between views

In module 4 of foundation 2023: lesson 03, why don’t we create a @binding for the city? It is confusing. please explain.

From the point of view of clarity in your question, are you referring to where city is passed to AttractionView and to CityViewCard from CityView?

Generally a Binding is used between two Views where the second View changes the data in the Binding which changes the @State variable in the calling View. An example might be where you present a View using a .sheet which is triggered by a binding boolean value which you declare as a @State variable and you pass that to the Second View. In that Second view you can change that value through it being declared as a @Binding in the second View.

Example code:

struct ContentView: View {
    @State private var isShowingSecond = false

    var body: some View {
        VStack(spacing: 30) {
            Text("Initial View")

            Button {
                isShowingSecond = true
                print("Showing Second Screen")
            } label: {
                Text("Show Second View")
            }
        }
        .fullScreenCover(isPresented: $isShowingSecond) {
            SecondView(isShowingSecond: $isShowingSecond)
        }
    }
}

SecondView:

struct SecondView: View {
    @Binding var isShowingSecond: Bool

    var body: some View {
        ZStack {
            Color.green
                .ignoresSafeArea()
            VStack(spacing: 30) {
                Text("Second View")
                    .font(.largeTitle)
                Button {
                    isShowingSecond = false
                } label: {
                    Text("Dismiss")
                        .font(.title)
                }
            }
        }
    }
}

In the case of the Guidebook App, all you are doing is passing an instance of City to the CityViewCard and the AttractionView in which neither of them need to change the underlying data.

You have asked the same question in another thread which I have deleted.

how to post code?

Do you mean, “How do you post code in a thread” like I have done above?

yes, I want to share the code here. Thanks

Thanks, I read and understand your explanation. You need to use @Binding and @State when you need to change the data store in either @State or @binding. But as you do not change any data in the guidebook, so you do not need to use @Binding and @State.

1 Like

In Xcode, use your cursor to select the block of code. Tap Command + C to Copy it.
Paste the code in the compose window and then select that block of code you just pasted in then click on the </> icon in the command bar above. See the following screenshot.

Then tap the icon <\> and it will format it as a code block which is indicated by the 3 back-ticks above and below the code. It will look like this in the Preview panel on the right.

I hope that all makes sense.

Thanks sir,