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

I tried to write an Int extension to bind Int to a specific range, for example:

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 realized what is being mininterpreted here as Int.min, which is a constant for the lowest Int.

I can override this by avoiding min/ max, but I'm curious: is there a way I can reference the extension from Int?

+4
source share
2 answers

You can add a 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 method clamp()from ClosedInterval.

+6

myMin<T>(a: T, b: T), min .

0

Source: https://habr.com/ru/post/1618392/


All Articles