How to pass binding to subview with SwiftUI when the variable is nested in an object?

The error is very misleading. Number must be a var, not a let:

struct MyStruct {
    var number: Int
}

Change it and it will work fine.


Your code was good except for needing var number: Int as kontiki pointed out.

To help with understanding of passing bindings about between views I prepared the following code which shows use of @Binding in slightly different ways:

import SwiftUI

struct Zoo    { var shed:    Shed     }
struct Shed   { var animals: [Animal] }
struct Animal { var legs:    Int      }

struct ZooView : View {
  @State var zoo = Zoo( shed: Shed(animals:
      [ Animal(legs: 2), Animal(legs: 4) ] ) )

  var body: some View {
    VStack {
      Text("Legs in the zoo directly:")
      Text("Animal 1 Legs: \(zoo.shed.animals[0].legs)")
      Text("Animal 2 Legs: \(zoo.shed.animals[1].legs)")
      Divider()
      Text("And now with nested views:")
      ShedView(shed: $zoo.shed)
    }
  }
}

struct ShedView : View {
  @Binding var shed: Shed

  var body: some View {
    ForEach(shed.animals.indices) { index in
      VStack {
        Text("Animal: \(index+1)")
        AnimalView(animal: self.$shed.animals[index])
      }
    }
  }
}

struct AnimalView : View {
  @Binding var animal: Animal

  var body: some View {
    VStack {
      Text("Legs = \(animal.legs)")
      Button(
      action: { self.animal.legs += 1 }) {
        Text("Another leg")
      }
    }
  }
}

In particular ShedView is given a binding to a shed and it looks up an animal in the array of animals in the shed and passes a binding to the animal on to AnimalView.

Tags:

Swift

Swiftui