Is absolute value of Duration not a thing?

Since Durations can be both negative and positive, is there not a abs() method to get the positive difference?

Yes, I can convert both to time intervals and create the absolute value of the double and cast that back to a returned duration in an extension. But do I need to do that? I think that will be ok because of my application domain and time resolution required, but is there a non lossy way?

Duration supports multiplication with scalars, so you could do something like this:

extension Duration {
    
    var abs: Duration {
        if self < Duration.zero {
            return self * -1
        }
        
        return self
    }
    
}

let dur = Duration(secondsComponent: -100, attosecondsComponent: 0)
print(dur.abs) // 100.0 seconds
1 Like

The abs generic function is constrained to Comparable & SignedNumeric, because AdditiveArithmetic didn't exist yet when it was written, which is why it isn't available on Duration. However, Duration has everything you need for it to be defined.

I would probably write it as:

func abs(_ a: Duration) -> Duration { 
    a < .zero ? .zero - a : a 
} 
2 Likes

Wouldn't a magnitude property be more "proper"?

Both are perfectly reasonable and in-line with existing stdlib API. A .magnitude property is more easily discoverable in most IDEs, however.

1 Like

Thanks everyone. These are good suggestions as I was lost in the weeds making it overly complicated. But yeah, having durations a little richer would be helpful in my migration to utilizing them. Specifically, having richer time formats such as mm:ss.SSS would be useful for my application domain.

FWIW, I think it would be a no-brainer tiny evolution proposal to add the .magnitude property, if someone wants to do that.

6 Likes