Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation error attempting to use `min()` function in Swift

Tags:

swift

I'm trying to write an extension for the Swift Int type to save nested min()/max() functions. It looks like this:

extension Int {
    func bound(minVal: Int, maxVal: Int) -> Int {
        let highBounded = min(self, maxVal)
        return max(minVal, highBounded)
    }
}

However, I have a compilation error when assigning/computing highBounded:

IntExtensions.swift:13:25: 'Int' does not have a member named 'min'

Why aren't the functions defined by the standard library properly located?

enter image description here

like image 212
Craig Otis Avatar asked Dec 25 '22 04:12

Craig Otis


1 Answers

It looks like it is trying to find a method in Int for min() and max() since you are extending Int. You can get 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)
    }
}
like image 51
Connor Avatar answered May 30 '23 21:05

Connor