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

2015-04-08

Swift Code Library: functions minmax and clippedMinMax

You are probably well aware of the functions:

func min<T : Comparable>(x: T, y: T) -> T
func max<T : Comparable>(x: T, y: T) -> T

When implementing functions that need a result in order we need to call both functions like:

let a = max(x, y)
let b = min(x, y)

Which is a bit laborious given that Swift has tuples that can be used to return values.

It would be nice to be able to write this as:

let (a, b) = minmax(x, y)

This is of course not all that difficult, I use the following implementation:

func minmax<T: Comparable>(first: T, second: T) -> (min: T, max: T) {
    let rmin = min(first, second)
    let rmax = max(first, second)
    return (rmin, rmax)
}

In addition, often I also have to safeguard the return values against minimum and maximum values. For that I use the following function:

func clippedMinMax<T: Comparable>(lowLimit: T, first: T, second: T, highLimit: T) -> (min: T, max: T) {
    let amin = max(lowLimit, min(highLimit, first))
    let amax = min(highLimit, max(lowLimit, second))
    return minmax(amin, amax)
}

This function can be called for example as follows:

let (a, b) = clippedMinMax(0, x, y, 100)

The function guarantees me that 'a' and 'b' will be in order, and that neither 'a' nor 'b' will be lower than 0 or higher than 100.

PS: I called the first function minmax rather than minMax because of similarity with the standard min and max functions. The clipped version deviates enough to fall back to my normal naming conventions.

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