Reputation: 1017
I am trying to determine the exact time the user has touched the screen. I have come up with this (inside my ViewController):
var startTime: Date?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
startTime = Date()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let endTime = Date()
print(endTime.timeIntervalSince(startTime!))
}
Seems to work pretty well.
Is this as precise as it gets?
Is there a way to test how precise this is?
Upvotes: 0
Views: 567
Reputation: 38833
I would go for the same structure as you have done it. Your print(endTime.timeIntervalSince(startTime!))
will print out a precise Double
value for you.
I would tweak it a bit though, check comments for explanations:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
startTime = Date()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// Don´t use startTime!, use if let instead
if let startTime = startTime {
// Use 2 decimals on your difference, or 3, or whatever suits your needs best
let difference = String(format: "%.2f", Date().timeIntervalSince(startTime))
print(difference)
}
}
Upvotes: 3