I'm trying to create a simple enough countdown timer using properties from a "Job" object, which I created, which holds a name: String, hours: Int, and mins: Int. It seems that on line 20 I receive an index out of range fatal error when I try to run it in the simulator, which is odd considering it doesn't have an issue beside not working quite right in the preview. Not to mention that in the context of running the whole app, I wouldn't access an array for this file. Code:
iimport SwiftUI import Combine
struct JobTimer: View {
@Binding var job: Job
@State var seconds = 0
@State var startDate = Date.now
@State var timeElapsed: Int = 0
@State private var cancellable: AnyCancellable?
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
let currentTime = Date.now
var body: some View {
Text("\(job.hours) : \(job.mins) : \(seconds)")
.onReceive(timer) { firedDate in
if job.hours == 0 && job.mins == 0 && seconds == 0 {
stopTimer()
}
if job.mins == 0 {
job.setHours(new: (job.hours-1))
job.setMins(new: 59)
}
if seconds == 0 {
job.setMins(new: (job.mins-1))
seconds = 59
}
else {
seconds -= 1
}
}
}
private func stopTimer(){
cancellable?.cancel()
}
}