你试图计算elapsedTime
是不正确的.在Swift 3中,它将是:
let elapsed = Date().timeIntervalSince(timeAtPress)
注意Date
参考后面的()
.Date()
实例化一个新的日期对象,然后timeIntervalSince
返回该对象与timeAtPress
之间的时间差.这将返回一个浮点值(技术上是TimeInterval
).
如果希望将其截断为Int
,可以使用:
let duration = Int(elapsed)
顺便说一句,timeAtPress
变量的定义不需要实例化Date
对象.我想你是有意的:
var timeAtPress: Date!
这将变量定义为Date
个变量(隐式展开的变量),但您可能会推迟该变量的实际实例化,直到调用pressed
为止.
或者,我经常使用CFAbsoluteTimeGetCurrent()
,例如.,
var start: CFAbsoluteTime!
当我想设置startTime
时,我会执行以下操作:
start = CFAbsoluteTimeGetCurrent()
当我想计算经过的秒数时,我会执行以下操作:
let elapsed = CFAbsoluteTimeGetCurrent() - start
值得注意的是,CFAbsoluteTimeGetCurrent
份文件警告我们:
重复调用此函数不能保证结果单调递增.由于与外部时间参考同步或由于用户明确改变时钟,系统时间可能会减少.
这意味着,如果不幸的是,当其中一个调整发生时,您测量了经过的时间,那么您可能会得到错误的经过时间计算.NSDate
/Date
计算也是如此.最安全的方法是使用基于mach_absolute_time
的计算(最容易使用CACurrentMediaTime
):
let start = CACurrentMediaTime()
和
let elapsed = CACurrentMediaTime() - start
它使用mach_absolute_time
,但避免了Technical Q&A QA1398中概述的一些复杂性.
Remember, though, that CACurrentMediaTime
/mach_absolute_time
will be reset when the device is rebooted. So, bottom line, if you need accurate elapsed time calculations while an app is running, use CACurrentMediaTime
. But if you're going to save this start time in persistent storage which you might recall when the app is restarted at some future date, then you have to use Date
or CFAbsoluteTimeGetCurrent
, 和 just live with any inaccuracies that may entail.