perhaps i am going crazy, but is there really no standard library API to convert a Duration to a Double of (milli)seconds?
next best thing i could think of is dividing by milliseconds(1). but this seems less efficient than doing the arithmetic manually.
let milliseconds:Double = duration / .milliseconds(1)
2 Likes
xwu
(Xiaodi Wu)
2
You’d compute it from components:
let seconds = Double(duration.components.seconds)
this loses the fractional component though?
1 Like
xwu
(Xiaodi Wu)
4
Ah, your question was ambiguous on that point; you'd add the attoseconds component back (appropriately scaled) for the fractional component, of course.
tera
5
Will this work?
extension Duration {
var inMilliseconds: Double {
Double((self * 1000).components.seconds)
Edit: no, that was not correct, this one is better:
extension Duration {
var inMilliseconds: Double {
let v = components
return Double(v.seconds) * 1000 + Double(v.attoseconds) * 1e-15
}
}
Gee, I've just corrected another mistake (was multiplying integer seconds - which may overflow)
Shouldn't this be in the standard library or was it deliberately not included?
2 Likes