Compilation error trying to use `min ()` function in Swift
I am trying to write an extension for Swift type Int
to preserve nested functions min()/max()
. It looks like this:
extension Int {
func bound(minVal: Int, maxVal: Int) -> Int {
let highBounded = min(self, maxVal)
return max(minVal, highBounded)
}
}
However, when assigning / calculating highBounded
, I have a compilation error:
IntExtensions.swift:13:25: 'Int' does not have a member named 'min'
Why aren't the functions defined by the standard library correctly defined?
+3
source to share
1 answer
It looks like it is trying to find a method in Int for min () and max () since you are extending Int. You can work around this and use the default min and max functions by specifying the Swift namespace.
extension Int {
func bound(minVal: Int, maxVal: Int) -> Int {
let highBounded = Swift.min(self, maxVal)
return Swift.max(minVal, highBounded)
}
}
+9
source to share