Search code examples
swifterror-handlingdo-catch

Nested do catch swift 3.0


I'd like to use consecutive try statements. If one returns an error I'd like to proceed to the next one, otherwise return the value. The code below seems to work fine, however I'll end up with a big nested do catch pyramid. Is there a smarter/better way to do it in Swift 3.0?

do {
    return try firstThing()
} catch {
    do {
        return try secondThing()
    } catch {
        return try thirdThing()
    }
}

Solution

  • If the actual errors thrown from those function calls are not needed then you can use try? to convert the result to an optional, and chain the calls with the nil-coalescing operator ??.

    For example:

    if let result = (try? firstThing()) ?? (try? secondThing()) ?? (try? thirdThing()) {
        return result
    } else {
        // everything failed ...
    }
    

    Or, if the error from the last method should be thrown if everything fails, use try? for all but the last method call:

    return (try? firstThing()) ?? (try? secondThing()) ?? (try thirdThing())