Elapsed Seconds in Swift
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.