Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing on unwrapping nil optional

Consider the following code:

enum MyErrorType:ErrorType {
    case BadTimes
}

var mightHaveAValue: String?

do {

    if let value = mightHaveAValue {
        // do stuff with value
    } else {
        throw MyErrorType.BadTimes
    }

    // do stuff with NSFileManager using mightHaveAValue which might throw

} catch {
    // handle error
}

...in which I have a large do/try/catch block. In this instance the error handling will be the same, whether mightHaveAValue is empty or something bad happens with NSFileManager later on. So it makes sense to re-use the error handling code.

Is this the cleanest approach going in Swift2, or is there some way I can automatically throw/catch on unwrapping an optional with no value?

like image 288
Andrew Ebling Avatar asked Oct 25 '25 07:10

Andrew Ebling


2 Answers

It looks ok, but it's even better with guard let instead of if let because it lets you use the unwrapped value in the main do block instead of having to work inside an if let branch. You can also use several catch branches to handle different error types.

do {

    guard let value = mightHaveAValue else {
        throw MyErrorType.BadTimes
    }

    // do stuff with value

} catch let error as MyErrorType {
    // handle custom error
} catch let error as NSError {
    // handle generic NSError
}

There is no automatic way to handle unwrapping optionals, you have to use one of the many known ways: if let, guard let, nil coalescing, etc.

like image 78
Eric Aya Avatar answered Oct 28 '25 04:10

Eric Aya


Maybe just use an extension like this 🤔

extension Optional {

    func throwing() throws -> Wrapped {
        if let wrapped = self {
            return wrapped
        } else {
            throw NSError("Trying to access non existing value")
        }
    }
}
like image 20
Ernest Jordan Chechelski Avatar answered Oct 28 '25 05:10

Ernest Jordan Chechelski