2

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 2

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.