the code:
class moveStruct: ObservableObject {
var moveIndex: Int
var moveTitle: String
var movePlayer: String
var moveColor: Color
init(moveIndex: Int, moveTitle: String, movePlayer: String, moveColor: Color) {
self.moveIndex = moveIndex
self.moveTitle = moveTitle
self.movePlayer = movePlayer
self.moveColor = moveColor
}
}
struct ContentView: View {
@State var theCounter: Int = 0
@State var theMoveArray = [moveStruct]()
@State var theArrayCounter = 0
var body: some View {
HStack {
var theMove = moveStruct(moveIndex: 0, moveTitle: "S", movePlayer: "Blue", moveColor: .blue)
var theMove2 = moveStruct(moveIndex: 1, moveTitle: "O", movePlayer: "Red", moveColor: .red)
Button {
theMoveArray.append(theMove)
theMoveArray.append(theMove2)
theCounter = 0
var theArrayBounds = theMoveArray.count - 1
\\print1
print("pre-timer count: \(theMoveArray.count)")
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
\\print2
print("in-timer count: \(theMoveArray.count)")
if theCounter <= (theArrayBounds) {
print("Timer fired!")
} else {
timer.invalidate()
}
theCounter += 1
}
print("Post-timer count: \(theMoveArray.count)")
theMoveArray.removeAll()
} label: {
Text("The Button")
.frame(width: 100, height: 100)
}
}
}
}
When I run this, outside of the timer, theMoveArray.count is 2 as expected. Inside the timer, it's 0. No idea why, but that's the problem.
Someone on StackOverflow said use @StateObject, but I'm not good with a lot of this, and when i try to init an array of moveStruct classes as an empty array:
@StateObject var theMoveArray = [moveStruct]() I get fussed at about "Generic struct 'StateObject' requires that '[moveStruct]' conform to 'ObservableObject'"
I'm at a loss here, I don't have any idea why this isn't working.