Marmelador
Marmelador

Reputation: 1017

Determining exact time between two touches

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

Answers (1)

Rashwan L
Rashwan L

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

Related Questions