1

The following code is simplified and isolated. It is intended to have a Text() view, which shows the number of times the button has been clicked, and a Button() to increment the text view.

The issue: Clicking the button does not actually change the Text() view, and it continues to display "1"

struct Temp: View {
    
    @State var h = struct1()

    var body: some View {
        VStack {
            Button(action: {
                h.num += 1
            }, label: {
                Text("CLICK ME")                
            })
            Text(String(h.num))
        }
    }
}

struct struct1 {
    @State var num = 1
}

What's funny is that the same code works in swift playgrounds (obviously with the Text() changed to print()). So, I'm wondering if this is an XCode specific bug? If not, why is this happening?

4
  • 1
    Take the State out of the struct that isn’t a SwiftUI View. It doesn’t belong there. Commented Dec 23, 2021 at 1:07
  • @lorem ipsum, this fixed it! thank you! I have zero idea why, though... could you make an answer, and maybe say why this worked? Commented Dec 23, 2021 at 4:36
  • The State property wrapper is for use in SwiftUI Views specifically, not just any struct. Commented Dec 23, 2021 at 9:29
  • @chuk do you mind accepting the answer? It is the green checkmark below Commented Dec 27, 2021 at 21:56

1 Answer 1

1

Remove @State from the variable in struct1

SwiftUI wrappers are only for SwiftUI Views with the exception of @Published inside an ObservableObject.

I have not found this in any documentation explicitly but the wrappers conform to DynamicProperty and of you look at the documentation for that it says that

The view gives values to these properties prior to recomputing the view’s body.

So it is implied that if the wrapped variable is not in a struct that is also a SwiftUI View it will not get an updated value because it does not have a body.

https://developer.apple.com/documentation/swiftui/dynamicproperty

The bug is that it works in Playgrounds but Playground seems to have a few of these things. Likely because of the way it complies and runs.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.