I'm not sure why this code doesn't work. It builds and runs fine, but nothing is displayed in the view. While debugging, I can see that the append() calls don't actually add the items to the array, but there's no error:
import SwiftUI
struct Test: View {
@State private var array: [String] = []
var body: some View {
self.array.append("A")
self.array.append("B")
self.array.append("C")
return VStack {
ForEach(self.array, id: \.self) {string in
Text(string)
}
}
}
}
struct Test_Previews: PreviewProvider {
static var previews: some View {
Test()
}
}
I've also tried doing the appends in an init(_:) with the same result. It works if I initialize the array with the values like @State private var array: [String] = ["A", "B", "C"] so it seems like there's some immutability of state variables nuance that I'm missing. I'm pretty new to Swift. Can someone please explain what I'm doing wrong here?