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

后端 未结 2 390
眼角桃花
眼角桃花 2020-12-06 21:37

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 {
    re         


        
相关标签:
2条回答
  • 2020-12-06 22:03

    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.

    0 讨论(0)
  • 2020-12-06 22:16

    You could create a function myMin<T>(a: T, b: T) that calls min and use that in your extension.

    0 讨论(0)
提交回复
热议问题