Skip to content

Instantly share code, notes, and snippets.

@joel-perry
Last active July 18, 2018 06:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joel-perry/17e02a92ae93d7208887 to your computer and use it in GitHub Desktop.
Save joel-perry/17e02a92ae93d7208887 to your computer and use it in GitHub Desktop.
Simple TapTempo class for Swift
class DTTapTempo {
private let timeOutInterval: NSTimeInterval
private let minTaps: Int
private var taps: [NSDate] = []
init(timeOut: NSTimeInterval, minimumTaps: Int) {
timeOutInterval = timeOut
minTaps = minimumTaps
}
func addTap() -> Double? {
let thisTap = NSDate()
if let lastTap = taps.last {
if thisTap.timeIntervalSinceDate(lastTap) > timeOutInterval {
taps.removeAll()
}
}
taps.append(thisTap)
guard taps.count >= minTaps else { return nil }
guard let firstTap = taps.first else { return nil }
let avgIntervals = thisTap.timeIntervalSinceDate(firstTap) / Double(taps.count - 1)
return 60.0 / avgIntervals
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment