是否可以在 Swift 中访问隐藏的顶级函数? [英] Is it possible to access a shadowed top level function in Swift?
问题描述
我试图编写一个 Int 扩展来将 Int 限制在特定范围内,如下所示:
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)
}
}
我收到一个编译器错误,过了一会儿我意识到min
在这里被解释为Int.min
,这是最低的常数Int
.
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
.
我可以重新实现这个避免 min
/max
但我很好奇:有没有办法可以从 Int
扩展中引用它们?
I can reimplement this avoiding min
/max
but I'm curious: is there a way I can reference those from an Int
extension?
推荐答案
你可以在前面加上模块名称,在这种情况下 Swift
:
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
}
}
使用 ClosedInterval
中的 clamp()
方法.
using the clamp()
method from ClosedInterval
.
这篇关于是否可以在 Swift 中访问隐藏的顶级函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!