计算通过的时间并更新所有任务

时间:2016-01-19 23:29:26

标签: swift

我正在创建一个待办事项列表应用程序,在几秒钟内倒计时直到下一个任务。

一旦完成一项任务,计时器开始倒计时直至下一个,依此类推。

当应用程序打开时,这会实时发生,但是当关闭时,计时器停止并且当前日期和时间存储在NSUserDefaults中,以便在打开时加载它们。

当应用程序打开时,我希望能够做这样简单的事情:

let nextTaskIn   = 600.0 // example of were the last task was
let appClosed    = "2016-01-19 23:00:49 +0000" // example of time closed really comes from NSDate set on close
let timePassed   = NSDate().timeIntervalSinceDate(appClosed) // get num of seconds changed
let nextTaskTime = nextTaskIn - timePassed // example 600.0 - 120.0 = 480 seconds left

然后我可以将文本标签更新为nextTaskTime一切都很棒!

然而,当时间过去比当前任务更长并且进入下一个任务时会出现问题。

例如:

let task1 = 90.0
let task2 = 180.0
let task3 = 270.0
let timePassed = 110.0
let nexTaskTime = task1 - timePassed // this is not correct

这不起作用,它应该做的是使task1 = 0.task2 = 160.0,但递归地通过所有或尽可能多的任务,直到没有任何剩余。

我最好的想法是让它发挥作用是一个循环,但我能想到的只是一个跟随,我已经没有想法了。

let task1 = 90.0
let task2 = 180.0
let task3 = 270.0
var timePassed = 110.0

while timePassed > 0 {
    let takenAway = timePassed - task1 // but unsure how to swap out for next task if task = 0
    timePassed = takenAway
} 

1 个答案:

答案 0 :(得分:1)

不确定这是否适合您的问题

let task1 = 90.0
let task2 = 180.0
let task3 = 270.0
var timePassed = 300.0
var tasks: [Double] = [task1, task2, task3] // init an array of your task

func updateTask(inout timePassed: Double) {
    for (index, _) in tasks.enumerate() { // enumerate your task
        let takenAway = timePassed - tasks[index]
        if takenAway <= 0 { // func should end here
            timePassed = 0
            tasks[index] = abs(takenAway)
            return
        }else { // keep going
            timePassed = takenAway
            tasks[index] = 0
        }
    }
}

updateTask(&timePassed)