Swift: should a function Throw or return an Optional?


Since Swift 2.0 we now have two ways for a function to fail:

  • It can return an Optional
  • Or it can Throw

Let’s use a very simple example: a function to return the square root of a number.
It is supposed to fail if the number was negative of course.

Return an Optional

func sqrt1(number: Float) -> Float? {
    guard(number >= 0) else {
        return nil
    }
    return sqrt(number)
}

func use1() {
    if let result = sqrt1(17) {
        print(result)
    } else {
        print("Error")
    }
}

Throw an exception

func sqrt2(number: Float) throws -> Float {
    guard(number >= 0) else {
        throw SqrtErrors.negativeNumber
    }
    return sqrt(number)
}

func use2() {
    do {
        let result = try sqrt2(17)
        print(result)
    } catch  {
        print("Error")
    }
}

Which style do you prefer? The obvious advantage of “throw” is that we get an ErrorType with information on the reason of the failure.
On the other side, Optional results can be chained and this can make it a much more convenient choice when we don’t care about the reason for failure.

,