Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access a shadowed top level function in Swift?

Tags:

swift

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?

like image 699
Jorge Bernal Avatar asked Feb 08 '23 09:02

Jorge Bernal


1 Answers

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.

like image 188
Martin R Avatar answered May 31 '23 05:05

Martin R