Skip to content

Instantly share code, notes, and snippets.

@irace
Created October 4, 2014 20:55
Show Gist options
  • Save irace/de6d576f49dc2eec9b18 to your computer and use it in GitHub Desktop.
Save irace/de6d576f49dc2eec9b18 to your computer and use it in GitHub Desktop.
A simple stopwatch in Swift
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
}
}
}
@duliodenis
Copy link

Nice!

@alessign
Copy link

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