Last active
July 18, 2018 06:09
-
-
Save joel-perry/17e02a92ae93d7208887 to your computer and use it in GitHub Desktop.
Simple TapTempo class for Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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