Skip to content

Instantly share code, notes, and snippets.

@texuf
Created May 17, 2018 00:14
Show Gist options
  • Save texuf/0b1da2ba28f002dba8ad23bc017dc5b5 to your computer and use it in GitHub Desktop.
Save texuf/0b1da2ba28f002dba8ad23bc017dc5b5 to your computer and use it in GitHub Desktop.
public class StopWatch {
private var elapsed: Double = 0
private var isRunning: Bool = false
private var startTime: Double = 0
public init() {}
public var elapsedTimeSeconds: Double {
if isRunning {
return elapsed + max(0, Date.timeIntervalSinceReferenceDate - startTime)
} else {
return elapsed
}
}
public func start() {
guard !isRunning else { return }
startTime = Date.timeIntervalSinceReferenceDate
isRunning = true
}
public func stop() {
guard isRunning else { return }
elapsed += max(0, Date.timeIntervalSinceReferenceDate - startTime)
isRunning = false
}
public func reset() {
isRunning = false
startTime = 0
elapsed = 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment