Passing @State to a subview’s @State

Let’s say you define a view using a @State variable X. And you define another view, used as a subview, also using a @State variable X2. And you pass X to X2, or some expression using X to X2.

Swift 5.1
struct Demo: View {
    @State var current: Double = 0
    var body: some View {
        VStack {
            VStack {
                Text((current == 0).description)
                Text((current == 1).description)
                Text((current == 2).description)
            }
            HStack {
                SingleView(isDownbeat: true, isCurrent: current == 0)
                SingleView(isDownbeat: false, isCurrent: current == 1)
                SingleView(isDownbeat: false, isCurrent: current == 2)
            }
            HStack {
                Text(String(Int(current)))
                Slider(value: $current, in: 0...2, step: 1.0)
            }
        }
        .padding()
        .background(style.background)
    }
}

struct SingleView: View {
    @State var current: Double = 0
    var body: some View {
        Text(String(current))
    }
}

Wellllp, that ain’t gonna make the subview update! It seems that the subview captures the initial X2 value and doesn’t think it’s changed…? Make X2 be a normal var and not @State and the subview will be recomputed/redrawn.

Swift 5.1
struct SingleView: View {
    var current: Double = 0
    var body: some View {
        Text(String(current))
    }
}

See: