Your attempt to calculate elapsedTime is incorrect. In Swift 3, it will be:
let elapsed = Date().timeIntervalSince(timeAtPress)
Note () after the Date link. Date() creates a new date object, and then timeIntervalSince returns the time difference between that and timeAtPress . This will return a floating point value (technically, TimeInterval ).
If you want this to be truncated to an Int value, you can simply use:
let duration = Int(elapsed)
And, BTW, your timeAtPress variable timeAtPress does not need to instantiate a Date object. I assume you intended:
var timeAtPress: Date!
Defines a variable as a Date variable (implicitly expanded), but you are supposed to postpone the actual creation of this variable until pressed is called.
Alternatively, I often use CFAbsoluteTimeGetCurrent() , for example,
var start: CFAbsoluteTime!
And when I want to set startTime , I do the following:
start = CFAbsoluteTimeGetCurrent()
And when I want to calculate the number of seconds elapsed, I do the following:
let elapsed = CFAbsoluteTimeGetCurrent() - start
It is worth noting that the CFAbsoluteTimeGetCurrent documentation warns us:
Repeated calls to this function do not guarantee monotonically increasing results. System time may be reduced due to synchronization with external time references or due to a user explicitly changing the clock.
This means that if you are fortunate enough to measure the elapsed time, when one of these adjustments occurs, you can complete the wrong time calculation. This is also true for NSDate / Date calculations. It is mach_absolute_time use calculations based on mach_absolute_time (most easily done using CACurrentMediaTime ):
let start = CACurrentMediaTime()
and
let elapsed = CACurrentMediaTime() - start
In this case, mach_absolute_time used, but avoids some of its complexities outlined in Technical Q & A QA1398 .
Remember that when the device is rebooted, CACurrentMediaTime / mach_absolute_time will be reset. So, on the bottom line, if you need accurate calculations of elapsed time while the application is CACurrentMediaTime , use CACurrentMediaTime . But if you are going to keep this start time in a permanent storage that you could remember when the application is restarted on some future day, then you should use Date or CFAbsoluteTimeGetCurrent and just live with any inaccuracies that may entail.