Elapsed Seconds in Swift

Gary Bartos
May 23, 2021

--

This whole post, even more briefly: the subtraction operator for the Date struct

The extension I use the most is likely the subtraction operator for the Date struct:

import Foundation

extension Date {
static func - (lhs: Date, rhs: Date) -> TimeInterval {
return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate
}
}

Do you want an easy bake method to measure how long it takes to run some code? Subtract the two Date instances to get the elapsed seconds.

let start = Date()
let result = myFunkyFunction()
let seconds = Date() - start

Following what I understand to be the standard naming convention for extensions, I use “+” in the name of the .swift file to indicate that it contains an extension.

Date+Diff.swift

With minor variations, you’ll find this extension in StackOverflow and elsewhere. My thanks go out to the pseudonymous coder whose sample code I found last year.

--

--

Gary Bartos
Gary Bartos

Written by Gary Bartos

Founder of Echobatix, engineer, inventor of assistive technology for people with disabilities. Keen on accessible gaming. echobatix@gmail.com

No responses yet