Created
May 17, 2018 00:14
-
-
Save texuf/0b1da2ba28f002dba8ad23bc017dc5b5 to your computer and use it in GitHub Desktop.
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
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