Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-09-21

Swift extensions: Comparable limiters

Your code will likely contain some of these kind of statements:

    var b = calculateValue(a)
    if b > limit { b = limit }

Typically this kind of construction is used on array indicies as well.

    var b = calculateValue(a)
    if b > array.count { b = array.count }

My problem with this construction is that it is not immediately clear what is being done, I have to read it to see that in fact this is no more than limiting the calculated value to a certain maximum.

Luckily most of the numbers that we need this for implement the Comparable protocol. This allows us to write a little extension:

extension Comparable {
    
    func limitTo(max max: Self) -> Self {
        if self < max { return self }
        return max
    }

    func limitTo(min min: Self) -> Self {
        if self > min { return self }
        return min
    }
    
    func limitTo(min min: Self, max: Self) -> Self {
        return self.limitTo(max: max).limitTo(min: min)
    }

    mutating func limitInPlaceTo(min min: Self) {
        if self < min { self = min }
    }
    
    mutating func limitInPlaceTo(max max: Self) {
        if self > max { self = max }
    }
    
    mutating func limitInPlaceTo(min: Self, max: Self) {
        self = self.limitTo(min:min, max: max)
    }
}

With this extension the above lines can be rewritten as:

    var b = calculateValue(a).limitTo(max: limit)

and

    var b = calculateValue(a).limitTo(max: array.count)

Of course the other functions can be used as well:

    b.limitInPlaceTo(min: limit)

Another advantage is that using these functions can change some of the variable definitions from a var to a let because it is no longer necessary to perform the limiting operation separate.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment