Predict the output
What happens when you build this and tap the button?
struct Counter: View {
var count = 0
var body: some View {
Button("Count: \(count)") {
count += 1
}
}
}Hint 1 of 1
Is self mutable inside a view's closures?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: C It doesn't compile: cannot assign to property, 'self' is immutable
Correct. Make it @State private var count = 0.
Why not the others?
- A The label counts up. The closure can't mutate
selfbecause the view is an immutable value. - B The label stays at 0. It never gets that far; the mutation is rejected at compile time.
- D It crashes at runtime. Swift catches this at compile time.