Migrating to Swift Duration

Excited to use the new Duration as I interact with several services that take different time units (microseconds as integers, etc). With regard to that, I am wondering if I am using it in the best way. Going from a TimeInterval is trivial:

let fromService: TimeInterval = 3.99999999
let duration = Duration.seconds(fromService)

I didn't see API for going the other direction so I added this little extension:

extension Duration {
  /// Possibly lossy conversion to TimeInterval
  var timeInterval: TimeInterval {
    TimeInterval(components.seconds) + Double(components.attoseconds)/1e18
  }
}

This seems to work fine, but I am wondering if I missed an affordance as the above seems a little hacky. :sweat_smile:

2 Likes

This looks alright to me. Perhaps multiply by 1e-18 instead of division, although I am not sure if this is any faster (in the past division was much slower than multiplication but these days?). Swift compiler doesn't change "/ 1e18" to "* 1e-18" (perhaps it should if multiplication is faster?).

Pedantically speaking conversion from TimeInterval to Duration is also lossy (considering durations shorter than 1e-18 or longer than 1e+19).

I was wondering about a similar thing before.