Why is DispatchTimeInterval not Comparable?


#1

I want to make a Range so that I could reason about relative ranges of time. I can’t because DispatchTimeInterval is not Comparable.

My intuition is that it could be, with ‘never’ being treated as ‘distant future’ and greater than any non-never value, but equal to other ‘never’ values.

Is there a reason this was not done?

In the end, it may not matter. Part of my goal had been to be able to do something like:

let range = .milliseconds(200) ..< .seconds(10)
let randomTimeInterval = DispatchTimeInterval.random(in: range)

But DispatchTimeInterval doesn’t support random either...


(Harlan Haskins) #2

This might be generally useful, but you can also add this conformance in an extension:

extension DispatchTimeInterval: Comparable {
  private var totalNanoseconds: Int64 {
    switch self {
    case .nanoseconds(let ns): return Int64(ns)
    case .microseconds(let us): return Int64(us) * 1_000
    case .milliseconds(let ms): return Int64(ms) * 1_000_000
    case .seconds(let s): return Int64(s) * 1_000_000_000
    case .never: fatalError("infinite nanoseconds")
    }
  }
  public static func <(lhs: DispatchTimeInterval, rhs: DispatchTimeInterval) -> Bool {
    if lhs == .never { return false }
    if rhs == .never { return true }
    return lhs.totalNanoseconds < rhs.totalNanoseconds
  }
}

DispatchTimeInterval.seconds(3) < .milliseconds(3000)

#3

I had tried something similar, with the extension, but had failed to understand how to get ahold of the internal raw value.

Thanks!