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.
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).
You can divide a duration by a Duration.seconds(1) to get a double of the duration in seconds (a TimeInterval), or a by a Duration.milliseconds(1) to get a double of that duration in milliseconds, etc.