SwiftUI cannot append to an array

Viewed 211

I'm trying to append to a list like this:

@State var activityTimes: [Double] = []
init(day: Day) {
        self.day = day
        self.addActivityTimes()
}

func addActivityTimes() {
        for (_, activity) in self.day.activities {
            let activityTime = Double((activity.hours * 60 * 60) + (activity.minutes * 60) + activity.seconds)
            self.activityTimes.append(activityTime)
        }
}

The append function does not seem to be working here and I'm not quite sure why that's happening.

2 Answers

This is not how State should be initialised. If I correctly understood your model here is a possible solution (tested with Xcode 12)

init(day: Day) {
    self.day = day

    let activities = day.activities.values.map { 
       Double(($0.hours * 60 * 60) + ($0.minutes * 60) + $0.seconds) 
    }
    self._activityTimes = State(initialValue: activities)
}

Just to add context here, any of the SwiftUI specific property wrappers can only be manipulated inside your View's body property. So you could do:

MyView()
  .onAppear { self.addActivityTimes() }

or

Button(action: { self.addActivityTimes() } { 
  Text("Add Activity") 
}

but you can't just populate it whenever you want to.

Related