I was trying to write an Int extension to clamp an Int to a specific range, like this:
extension Int {
func clamp(left: Int, right: Int) -> Int {
return min(max(self, left), right)
}
}
I was getting a compiler error and after a while I realised that min
is being interpreted here as Int.min
, which is a constant for the lowest Int
.
I can reimplement this avoiding min
/max
but I'm curious: is there a way I can reference those from an Int
extension?
You can prepend the module name, in this case Swift
:
extension Int {
func clamp(left: Int, right: Int) -> Int {
return Swift.min(Swift.max(self, left), right)
}
}
And just for fun: You get the same result with
extension Int {
func clamp(left: Int, right: Int) -> Int {
return (left ... right).clamp(self ... self).start
}
}
using the clamp()
method from ClosedInterval
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With