arraysswiftuiobservablestate

How to keep track of changes of objects in my array


I try to develop my first app, which is a quiz app. Here is my class for the Quiz player:

class QuizPlayer: ObservableObject {
    @Published var name: String
    @Published var points: Int
    @Published var isActive: Bool
    @Published var isPartOfTheCurrentRound: Bool
    @Published var pointsThisRound: Int
    @Published var playerColor: Color

    init(name: String, playerColor: Color) {
        self.name = name
        self.points = 0
        self.isActive = false
        self.isPartOfTheCurrentRound = true
        self.pointsThisRound = 0
        self.playerColor = playerColor
    }

    func addPoints(pointsToAdd: Int) {
        self.points += pointsToAdd
    }
}

In my view I initialize 5 players as follows:

@State var quizPlayers: [QuizPlayer] = [
        QuizPlayer(name: "", playerColor: Color.blue),
        QuizPlayer(name: "", playerColor: Color.orange),
        QuizPlayer(name: "", playerColor: Color.yellow),
        QuizPlayer(name: "", playerColor: Color.pink),
        QuizPlayer(name: "", playerColor: Color.brown)
]

The problem is: When for example I change the points of one player in a View, the View should pre-render because I want all variables of ALL players to be observed. However that doesn't do anything and it's not re-renderung. I think there is a problem with the array and that I should initialize my players each as an observable object. However it's much easier to use them in an array. Anybody has a idea how I can make all my properties of each player to be observed, while keeping my players in a array?

I tried to initialize each of them as a observable object, but wasn't able to put them into a array afterwards.


Solution

  • Just change:

    class QuizPlayer: ObservableObject {
    

    to

    struct QuizPlayer {
    

    And remove all remove all @Published, then change:

    func addPoints(pointsToAdd: Int) {
    

    to

    mutating func addPoints(pointsToAdd: Int) {