Swift-Snippets: A Max Function for Optionals

March 22, 2015

The other day I needed to compare several values to determine which one was the maximum. Great, there is a max function built into the swift language!

One catch, that max function only takes unwrapped values and I needed to compare optionals. Simply unwrapping these optionals and then calling the built in max function doesn’t scale because you have the same number of permutations as the max comparison implementation itself. Therefore, I decided to write a generic max function that takes optionals:

public func max(x: T?, y: T?) -> T? {
    if let vx = x {
        if let vy = y {
            return max(vx,vy)
        } else {
            return x
    } else {
        return y

public func max(x: T?, y: T?, z: T?) -> T? {
    return max(max(x,y),max(y,z))

When writing this code the compiler continuously had an error tantrum being unable to decide whether I was calling the newly defined max function or the built in one. I had expected that it would be clear to the compiler which function to call based upon the argument value types, but I guess not. To get around this problem I had to make this a public function within a base framework we use in our app so I could use it in our other frameworks/apps.

Check it out on Github, a suite of unit tests verify it works great!