WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: How to pass a variable backwards and forward between views?

Forums > Swift

The title isn't very clear but this is what I want to do:

ForEach(tortoises.items, id: \.name){ item in
                                VStack{
                                    Text("Name: \(item.name)")
                                        .font(.title)
                                    Text("Age: \(item.age)")
                                        .font(.title)
                                    NavigationLink("Change Age"){
                                        AgeChange(age: item.age) 

                                    }

I want to change item.age using this picker in a different view

Here is the view:


struct AgeChange: View{
    @State var age: Int
    var body: some View{
        Picker("Age:", selection: $age){
            ForEach(0..<120){
                Text("Age: \($0)")
                    .font(.title)

            }
        }
    }
}

   

This is because in your AgeChange you declared age as @State. Basically, it means, that your age variable is owned by this view. Which is not. You need a Binding.

https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-binding-property-wrapper

I changed your variable name just to create my own examples.

NavigationView {
    List($myTortoises, id: \.name) { $item in
    VStack{
        Text(item.name)
        .font(.title)
      Text("Age: \(item.age)")
          .font(.title)
            NavigationLink("Change Age"){
        AgeChange(age: $item.age)                
            }
        }
    }
}
struct AgeChange: View{
    @Binding var age: Int

    var body: some View{
    Picker("Age:", selection: $age){
        ForEach(0..<120){
        Text("Age: \($0)")
            .font(.title)
      }
    }
  }
}

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.