spigen
spigen

Reputation: 81

Milliseconds in Swift

I have the following snippet to display seconds, how can i show milliseconds?

// update timer
func updateTime() {
    second++
    if  second == 1 {
        second++
    }
    secondTimeLabel.text = "\(second)"
}

Upvotes: 0

Views: 2681

Answers (2)

Błażej
Błażej

Reputation: 3635

Since base unit in NSTimeInterval is seconds then use 0.001 is milliseconds.

So you can use it like this

let milisecond = 0.001 //NSTimeInterval
NSTimer.scheduledTimerWithTimeInterval(millisecond, target: self, selector: "milisecondTick:", userInfo: nil, repeats: true)

func milisecondTick(timer:NSTimer) {
    guard let date = timer.userInfo as? NSDate else {
        timer.invalidate()
        return
    }

    let passedMilliseconds = NSDate().timeIntervalSinceDate(date)
    millisecondTimeLabel.text = "\(passedMilliseconds)"
}

Upvotes: 0

Allen
Allen

Reputation: 1734

NSTimeInterval is a double value and can show milliseconds.


    NSTimer.scheduledTimerWithTimeInterval(0.1, target: self,
        selector: "printDuration:",
        userInfo: NSDate(),
        repeats: true)

    func printDuration(timer: NSTimer) {
        guard let userInfo = timer.userInfo else {
            return
        }

        guard let startDate = userInfo as? NSDate else {
            return
        }

        print("duration: \(NSDate().timeIntervalSinceDate(startDate))")
    }

Upvotes: 1

Related Questions