swiftnstimeinterval

How to convert DispatchTimeInterval to NSTimeInterval (or Double)?


I need to subtract a DispatchTimeInterval from an NSTimeInterval (or Double).

Is there a standard way to convert a DispatchTimeInterval to an NSTimeInterval?


Solution

  • A very neat and simple solution is this one (no need for switch statements):

    extension DispatchTimeInterval {
      var nanoseconds: UInt64 {
        let now = DispatchTime.now()
        let later = now.advanced(by: self)
        return later.uptimeNanoseconds - now.uptimeNanoseconds
      }
    
      var timeInterval: TimeInterval {
        return Double(nanoseconds) / Double(NSEC_PER_SEC)
      }
    }