Created
October 4, 2014 20:55
-
-
Save irace/de6d576f49dc2eec9b18 to your computer and use it in GitHub Desktop.
A simple stopwatch in 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
import Foundation | |
/** | |
* A really simple timer that I didn't want to call `Timer` because timer means something else in Foundation. | |
*/ | |
@objc class Stopwatch: NSObject { | |
private var startTime: NSDate? | |
var isRunning: Bool { | |
return startTime != nil | |
}; | |
func start() { | |
startTime = NSDate.date() | |
} | |
func stop() -> NSTimeInterval { | |
if let time = startTime { | |
startTime = nil | |
return NSDate.date().timeIntervalSinceDate(time) | |
} | |
else { | |
return 0 | |
} | |
} | |
} |
Swift 3:
@objc class Stopwatch: NSObject {
private var startTime: NSDate?
var isRunning: Bool {
return startTime != nil
};
func start() {
startTime = Date() as NSDate
}
func stop() -> TimeInterval {
if let time = startTime {
startTime = nil
let endDate = Date() as NSDate
return endDate.timeIntervalSince(time as Date)
}
else {
return 0
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!