Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
    }
}
like image 410
Mymodo Avatar asked Aug 14 '17 10:08

Mymodo


2 Answers

If Martin's answer is too terse for your taste you can just go with individual catch blocks.

do {
    return try firstThing()
} catch {}

do {
    return try secondThing()
} catch {}

do {
    return try thirdThing()
} catch {}

return defaultThing()

As each throwing function's result is immediately returned no nesting is necessary.

like image 88
Nikolai Ruhe Avatar answered Sep 24 '22 21:09

Nikolai Ruhe


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())
like image 24
Martin R Avatar answered Sep 22 '22 21:09

Martin R