Last active
June 25, 2018 22:49
-
-
Save RustyKnight/606451a1ab685dffee739f3c031ea30a to your computer and use it in GitHub Desktop.
Simple implementation of a "clock" or "stop watch", capable of been paused
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
import Foundation | |
class AlarmClock: SimpleClock { | |
var timeout: TimeInterval = 0 | |
var hasExpired: Bool { | |
return duration >= timeout | |
} | |
var timeRemaining: TimeInterval { | |
return max(timeout - duration, 0) | |
} | |
} |
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
import Foundation | |
public class SimpleClock { | |
internal var startedAt: Date? = nil | |
internal var totalRunningTime: TimeInterval = 0 // Used for pause/resume | |
var isRunning: Bool = false { | |
didSet { | |
if isRunning { | |
startedAt = Date() | |
} else { | |
totalRunningTime += currentCycleDuration | |
self.startedAt = nil | |
} | |
} | |
} | |
// This is the amount of time that this cycle has been running, | |
// that is, the amount of time since the clock was started to now. | |
// It does not include other cycles | |
internal var currentCycleDuration: TimeInterval { | |
guard let startedAt = startedAt else { | |
return 0 | |
} | |
return Date().timeIntervalSince(startedAt) | |
} | |
func reset() { | |
isRunning = false | |
totalRunningTime = 0 | |
} | |
// This is the "total" amount of time the clock has been allowed | |
// to run for, excluding periods when the clock was paused | |
var duration: TimeInterval { | |
return totalRunningTime + currentCycleDuration | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment