Craig Otis
Craig Otis

Reputation: 32074

Compilation error attempting to use `min()` function in 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

Upvotes: 4

Views: 292

Answers (1)

Connor
Connor

Reputation: 64654

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)
    }
}

Upvotes: 10

Related Questions