Motivation
It is a common pattern to have a throwing function whose result needs to be bound for use in the enclosing scope.
let value = try thrower()
// We want to handle any thrown errors and exit early
// so that the value binding can stay un-nested.
use(value)
There are a few ways to achieve this today, none of which are ideal.
do/catch
The do/catch versions have multiple issues:
do {
let value = try thrower()
use(value) // The happy path is nested
} catch {
// Error handling is visually separated from the point
// of origin of the error in code, especially when the
// happy path is particularly long.
log(error)
return
}
Wrapping more code in the do also widens what the catch handles: a throw from use(value) is caught by the same block, even if that was not intended. There is a better version, but that has its own issues:
// Declaration is split from initialization
let value: Value // A type annotation becomes necessary
do {
value = try thrower()
} catch {
log(error)
// Unlike guard statements, do statements aren't generally
// associated with early exit, so its harder to visually
// verify that the code indeed exits early when it should.
return
}
use(value)
try?
Alternatively, try? allows a concise guard statement, which is the idiomatic way to bind a conditionally existing value, with early exit on failure. However, it loses information on the error value itself.
guard let value = try? thrower() else {
// The error value is lost so no specialized error
// handling is possible.
return
}
Result
Result avoids the nesting and keeps the error, but it needs a wrapper at the call site and a second pattern match to retrieve the error.
// A Result {} wrap becomes necessary at the call point.
// Combined with the .success pattern matching, it is a lot of
// ceremony for such a common use case.
//
// The binding also needs to be separate from the guard to allow
// pattern matching twice, once for the value and once for the
// error, though this is mostly down to code preference.
let result = Result { try thrower() }
guard case let .success(value) = result else {
// A second pattern match is required to retrieve the error,
// even though failure of the .success pattern guarantees it.
if case let .failure(error) = result {
log(error)
}
return
}
use(value)
The issue is so common that there has been a whole history of pitches/discussions trying to solve this very issue. This pitch takes design elements/inspiration and incorporates feedback from all of these:
- Extend "guard" to try-statements, with a catch block (2016). First proposed
guard let x = try foo catch { ... }. Chris Lattner objected thatguard letmust keep meaning "match an optional" and thattryalready means "propagate", so a latercatchshould change neither. He suggested putting the behavior on the binding (let x = try foo() catch { ... }), withelsepluscatchfor optional-returning throwers, both required to exit. Jordan Rose suggestedguard try let x = foo() catch, noting thattrycannot be limited to part of the expression. This pitch leavesletandtryunchanged and gives the new meaning to a separatedomarker. - Guard/Catch (2017) and its written proposal. It was submitted as a formal proposal but closed after core team pre-review. The core team agreed the problem is worth solving, but considered it unacceptable for the meaning of
guard let x = ...to depend on whetherelseorcatchfollows, and noted that building this intoguardimplies anifequivalent. The authors had also set aside combiningcatchwithelse, since it raised unanswered questions about the bound type, clause order, and whetherelsemay sit betweencatchclauses. This pitch addresses these with a separatedomarker, soguard letandtryare unchanged. - Is it possible to make early exit in do-try-catch block? (2019). Participants proposed
guard/catchand a guard-likedo-guard let a = try f(), let b = try g() catch { ... }. One contributor proposed requiringcatchwhen any condition usestryandelsewhen any condition unwraps or tests. This pitch uses the same rule, keyed on an explicitdomarker so that a plaintrycondition still propagates. The thread also warned that letting an unmatched error fall through toelsewould swallow it, so unmatched errors propagate here instead. - Guard-like syntax for do/catch (2021). Proposed
do let value = try f() catch { ... },guardwithelseandcatch, and a value-returningdo. - Guard-Let-Catch (and If-Let-Catch) (2023). Proposed
catchonguard/ifwhenever the condition containstry. Replies noted thatdoexpression branches cannotreturn, and asked how to tell which of several statements failed. - Introducing do-let-catch (Oct 2024). Proposed
do let (data, response) = try await ... catch { throw ... }, withoutguard. A reply argued that ado/catchvariant should not force early exit, and another showed thatdoexpressions cover the case where thecatchrethrows. This pitch keepsguardso that exit is guaranteed. - Guard that works with 'try' (Jun 2025). Proposed
guard let x = try f() else { ... }with an impliciterror; replies objected that this conflicts with optional unwrapping. - Un-nesting the happy path when catching errors (Feb 2026). Proposed a trailing
expr catch { ... }, bracelessdo try ... catch,do/catchexpressions, andguard try let x = f() else { ... }. - Pitch:
guard try(Mar 2026). Proposed separateelseandcatchblocks onguard, with no marker. Replies proposed a bracelessdo guard, a bracedguard do { ... } catch { ... }, anddo/catchexpressions. Michel Fortin's reply placed adomarker inside the condition, the closest prior art for this pitch.
The motivation this proposal sets out with is a clean way to bind variables to throwing functions, and handling any errors in place with early exit guarantees.
Proposal
We introduce a new do marker for guard conditions. Errors thrown by a do-marked condition are caught by the catchblocks of the guard.
guard do let value = thrower() catch {
// Implicit error variable as in catch blocks
log(error)
return
}
// guard guarantees exit on error so value is bound
// in the non-nested scope; traditional guard behavior.
use(value)
A do let condition is a plain binding. No optional unwrapping or condition check is performed, so if thrower()returns Int?, then value is an Int?, and a nil result is a success. This is similar to how the case marker already behaves.
Rules
- Marking a non-throwing expression as
dois a "guard condition is always true" warning. - A guard containing any
docondition requires at least onecatchblock. If there are nodoconditions, havingcatchblocks is a dead code warning. - A guard containing any non-
docondition requires anelseblock. If there are no non-doconditions, having anelseblock is a dead code warning. catchblocks, just likeelseblocks, must exit the current scope.catchandelseblocks may be written in either order, and the order does not change their meaning.catchblocks handle errors thrown bydoconditions only. Atryanywhere else in the guard propagates as it does today, and errors thrown from inside anelseorcatchbody also propagate.- Bindings introduced by the guard are not in scope inside its
catchandelseblocks, as withguardtoday. - Mixed markers like
do case letare beyond the scope of this pitch.
Since do can only mark throwing expressions, the try annotation becomes redundant and can be skipped.
Just like in traditional do statements, catch blocks following a guard can be multiple in number and support all the relevant pattern matching. Also like traditional do statements, the catch blocks need not be exhaustive. Any uncaught error propagates, and error propagation exits the current scope, preserving the guarantee of guard. The enclosing context must be able to throw in that case, the same check do/catch performs today.
guard do let value = anyErrorThrower()
catch is Error1 {
return
} // Any other error propagates, exiting the current scope
use(value)
Type inference for the implicit error variable is the same as in do statements.
// Same type inference as catch blocks in `do` bodies.
guard do let value = error1Thrower() catch {
// error: Error1 with FullTypedThrows feature flag
// error: any Error otherwise
return
}
guard do let value1 = error1Thrower(),
do let value2 = error2Thrower() catch {
// error: any Error
return
}
Mixing with other conditions
As with other guard patterns, do can be used in tandem with other conditions, so catch and else blocks may co-exist.
guard do let value1 = error1Thrower(),
do let value2 = error2Thrower(),
let value3 = try throwingOptionalReturner(),
boolReturner()
catch let error as Error1 {
// error1Thrower() threw.
log(error)
return
} catch {
// Handles any other error from a `do` condition. If this
// block is removed, unhandled errors propagate.
// Errors from `try throwingOptionalReturner()` never get
// here since that condition is not marked `do`.
return
} else {
// One of the non-`do` conditions failed:
// `try throwingOptionalReturner()` returned nil, or
// `boolReturner()` returned false.
return
}
// All three bindings are available, and boolReturner() was true.
use(value1, value2, value3)
value1 and value2 are bound exactly as returned. Only value3 is unwrapped, because only that clause is an ordinary guard let unbinding.
The catch and else blocks may be present in any order.
Other forms
The do marker also has a do var variant for mutable bindings, just like the other guard markers. Standard irrefutable pattern matching can be done on the binding side as per let/var rules.
guard do var (a, b) = throwingTupleReturner() catch { ... }
print(a, b)
Not binding any variables is also possible with just do <expr>. The result of the expression, if any, is discarded.
guard do throwingVoidReturner() catch {
log(error)
return
}
// un-nested happy path.
This last form is not central to the pitch and can be dropped if it makes the rest harder to justify.
Why guard/do/catch?
guard is the natural spelling for this feature for a few reasons:
guardis the idiomatic way to bind conditionally existing variables to the current scope, as seen inguard letfor optionals andguard case letfor pattern matched values.- Swift programmers are used to seeing
guardas an indication for early-exit which other spellings don't provide.
The do marker solves quite a few issues present in the other spellings:
guard let ... catch {}either does two things at once (error catching and optional unwrapping), or breaks a learned code pattern in aguard letnot unwrapping an optional, which was the core team's stated objection to the 2017 pitch.- Marking
guardstatements has precedent inguard caseand gives the feature a visually consistent with other language patterns:dosignaling error handling and no confusingguard letnot unwrapping patterns.
A separate catch block is used for do conditions instead of reusing the standard else block because the blocks are behaviorally equivalent to the catch blocks of a do statement, with pattern matching, implicit error binding, typed throws, and propagation.
This pitch does not aim to replace do/catch as the general mechanism for handling errors. Rather, it addresses a particular use case where guard already offers a useful advantage.
Alternatives considered
do/catch, try?, and Result
Discussed in the Motivation section.
non-guard spellings
As discussed in the "Why guard/do/catch" section, non-guard spellings for this feature aren't idiomatic. Still some of the popular suggestions are discussed below in a bit more detail.
doexpressions
do expressions, as pitched in Last expression as return value, would let a do/catch produce a value:
let result: Value? = do {
try thrower()
} catch {
log(error)
nil // No early exit
}
// A second condition is needed for early exit.
guard let value = result else { return }
Accepted Swift expression mechanics (see SE-0380 (Accepted)/Control Flow section) restricts control flow out of expressions to thrown errors; they cannot return. The catch branch above therefore cannot exit the scope through a return statement.
The error is collapsed into nil, the else cannot tell a thrown error from an absent value, and non-optional results need an Optional wrapper. This pitch provides the early exit of guard with the error still in hand, so the two features are complementary.
A related suggestion is to relax the branch rules so that a catch can exit, for example let x = do try f() catch { log(error); return }. That would be a larger change to expression semantics, and it would be a different feature from this one: the binding would be unconditional, not a guard condition that composes with others in the same list. And the reasons behind preferring the guard spelling still apply.
- Braceless
doand trailingcatch
Several replies proposed making the braces of do optional
do guard let value = try thrower() else { ... } catch { ... }
// Or attach catch directly to an expression.
let value = try thrower() catch { ... }
A braceless do can be read as covering the elsebody, which is the opposite of what this pitch does. In do guard ... else { throw A } catch { ... }, a reader cannot tell whether catch handles A. Here, only do-marked conditions are caught, so errors thrown from an else or catch body always propagate.
A trailing catch on a plain expression would either not have a guaranteed exit condition and thus be the same as do expressions, or it will and clash with the domain of the existing guard feature, which would need some heavy justification.
- Guard-like
doconditions
do let a = try f(), let b = try g() catch { ... } puts the list at statement level instead of inside guard. It cannot be combined with else and does not guarantee an early exit, so the bindings could not be used in the enclosing scope. Again, guaranteeing early exit would fight with the domain of guard statements.
Braced guard do { ... } catch { ... }
A braced form could cover several statements. It would also bring back the nesting and scoping this pitch avoids, and guard do { could be ambiguous with future do expressions.
Un-marked guard conditions
This is by far the most common suggestion in the threads I went through, and one that has been explicitly declined by the core team (see Add a proposal for guard-catch).
The guard try pitch uses no marker: else and catch blocks are attached to an ordinary condition list. A reviewer there asked what the bound type is when the expression is not optional, and the original pitch did not specify it. Without a marker, the type depends on a clause that follows the binding:
func f() throws -> Int? { /* ... */ }
guard let value = try f() else { return } // propagates; value: Int
guard let value = try f() catch { return } // caught; value: Int?
guard let value = try f() catch { return } // caught; value: Int
else { return }
guard let normally promises a non-optional value, so having a trailing clause decide that is easy to misread. The domarker states at the start of the clause that the error is caught and that no unwrapping is implied.
guard try instead of do
guard try can be considered to be in some ways more natural than guard do. This pitch uses do for two reasons:
trymarks a call site that can throw, whiledoestablishes where errors are caught.dois the keyword that already says "errors stop here".- A leading
tryin a guard condition is legal today and means the opposite: the error propagates.
// The error propagates; the Bool controls execution.
guard try throwingBooleanReturner() else { return }
// The error would be caught; the Bool would be ignored.
guard try throwingBooleanReturner() catch { return }
These two differ only by the trailing keyword, which is easy to misread.
Requiring try inside a do clause
Since a non-throwing expression cannot be marked do, the marker can be read as an implicit leading try. try covers everything to its right, so one marker at the head of the initializer covers the whole expression: try throwing(try throwing()) can be spelled try throwing(throwing()).
guard do let value = a(b(c())) catch { return }
This makes it so that the exact throwing calls aren't marked, but given the right-coverage property of try, that seems suitable, and thus this pitch chooses brevity here. Requiring try would keep every throwing call individually marked, but would put two keywords where one conveys the meaning, which is most visible when nothing is bound:
guard do try throwingVoidReturner() catch { return }
A point against this is that currently swift only allows error propagation from points explicitly marked try/throw, but again see the try's right coverage point. Feedback is encouraged for this point.
Requiring exhaustive catch blocks
An alternative is to require the catch blocks to be exhaustive, so that every error from a do condition is handled where it occurs and never propagates. This would make the exit guarantee come only from the catch blocks, and it would keep propagation from being invisible when try is elided. This pitch does not require it, for these reasons:
do/catchdoes not require it, and following its rules keeps the pitch small.- Propagation is
guard-compatible. It exits the scope, so the guarantee holds. - Requiring a catch-all would force boilerplate in the common case where the caller handles most errors. A function that only wants to special-case
FileNotFoundwould needcatch { throw error }.
Given that try is optional as per the current pitch (see “Requiring try inside a do clause”) propagation from a do condition is not marked at the call site, which can be considered non-ideal. Feedback is encouraged for this point.
Order of else and catch
The 2017 gist asked whether an order must be prescribed, and some replies preferred catch before else so that catchvisibly does not cover the else body. Because only do conditions are caught, either order has the same meaning here.
This pitch allows either order since for guard statement with multiple conditions, some do and some case or optional unwrapping, users might want the block order to match the statement order. For a similar reason, the two types of blocks can also be interleved.
guard do let value1 = error1Thrower(),
let value2 = optionalReturner(),
do let value3 = error2Thrower()
catch is Error1 { ... } // 1st condition handler
else { ... } // 2nd condition handler
catch is Error2 { ... } // 3rd condition handler
Feedback is encouraged for this point.
Source compatibility
This change is additive. The do keyword cannot begin a guard condition today, so no existing code changes meaning. The one form not distinguished by a following let or var is guard do <expr>; if do expressions later become legal in conditions, that form's parse would need to be settled alongside them.
ABI stability
No effect on ABI.