Pitch: `guard try` — error-aware early exit

What would happen to the try's there? Or will I need to nest another do {} catch {} in the else part?!

Sure. Here's my suggestion:

// Proposed                     Today's equivalent
                          |
do while try foo() {      |     do { while try foo() {
    try bar()             |         try bar()
} catch {                 |     }} catch {
    // all caught here              // all caught here
}                         |     }
                          |
do try foo() catch {      |     do { try foo() } catch {
    // caught here                  // caught here
}                         |     }
                          |
do if try foo() {         |     do { if try foo() {
    try bar()             |         try bar()
} else {                  |     } else {
    try baz()             |         try baz()
} catch {                 |     }} catch {
    // all caught here              // all caught here
}                         |     }
                          |
do guard try foo() else { |     do { guard try foo() else {
    try bar()             |         try bar()
    return                |         return
} catch {                 |     }} catch {
    // all caught here              // all caught here
}                         |     }

These is how I envision the examples brought above should look:

do guard let data = try fileHandle.read(upToCount: 1024) else {
    return
} catch {
    logger.error("\(error)")
    return
}
let payload = do try JSONEncoder().encode(something) catch {
    logger.error("Failed to encode: \(error)")
    return
}

IOW - almost as today... just without braces for the do expression (plus today we don't have do expressions yet (which was a future direction of SE-0380.

3 Likes