I recently encountered a scenario where I found the existing syntax in Swift unnecessarily complex and less readable:
let data: Data
let response: URLResponse
do {
(data, response) = try await URLSession.shared.data(for: request)
} catch {
throw RequestError.failedToLoadData(error)
}
I believe it would be far more readable and concise if we could write it this way:
do let (data, response) = try await URLSession.shared.data(for: request) catch {
throw RequestError.failedToLoadData(error)
}
Note how I didn't even have to specify the types of data
and response
and could profit from Swift's type inference, which isn't possible with today's code. It's also just 3 lines instead of 7.
Currently, Swift’s do-catch
syntax requires both do
and catch
to be followed by full code blocks inside curly braces, similar to the traditional if-else
structure. However, Swift introduced the guard-let-else
construct, which improved readability and reduced boilerplate by replacing the if
body with a more compact let
expression. This was a significant step forward in making code more concise without sacrificing clarity.
Considering that unwrapping an Optional
(which can fail) is conceptually similar to executing throwing code (which can also fail), it seems only natural to apply a similar simplification. When an Optional
fails, it evaluates to nil
, whereas when throwing code fails, it passes an error to the catch
block. Given this similarity, I propose extending this idea to do-catch
by introducing a do-let-catch
syntax.
This new syntax would allow us to write a let
expression after the do
, similar to how guard-let-else
works. It would allow for multiple let
expressions separated by commas, like so:
do let x = try foo(), let y = try bar() catch {
// handle error, must return or throw like in a `guard` block
}
// x and y are available here
This approach would not only make code more compact but also more aligned with Swift’s design philosophy of clarity and expressiveness. It feels like a natural progression that has simply been overlooked so far.
What are your thoughts on this potential improvement?