Guard-Let-Catch (and If-Let-Catch) to avoid long (nested) do-blocks

This is a fantastic pitch and this language problem should've been solved a long time ago. This pitch tackles this problem in a way that is simple, readable, and uses concepts and mechanisms that are already familiar in the language.

2 Likes

This code is precisely the problem with the current syntax. This code is filled with extra noise.

2 Likes

Looking at this from slightly different angle... Once we have 1) do expressions implemented, and on top of that 2) allow omitting braces when do block has only one statement / expression → we may end up with something that looks very similar to what you are asking:

  let (data, response) = do try await URLSession.shared.data(for: request) catch {
     throw RequestError.failedToLoadData(error)
  }
  let (data, response) = do { try await URLSession.shared.data(for: request) } catch {
     throw RequestError.failedToLoadData(error)
  }

This doesn't seem onerous enough to me that the braces should ever be made optional.

2 Likes

I really like this idea, in some form or another. Slightly off-topic: A related issue I often have with throwing functions is when I want to do something like

  • try x()
  • if x throws, try y()
    etc

Currently it seems that I have to put the backup calls in increasingly nested catch blocks, and as much as I like this pitch, it doesn't seem to help this particular inconvenience. I wonder if there is a common solution to both problems?

2 Likes

I don't think those two features alone are quite enough.

On top of do expressions and omitted braces, being able to throw from the catch branch would still additionally require the pitched Never as bottom type including the mentioned future direction where throw statements would count as Never-valued expressions.

1 Like

Any news about do expressions? Those seem to solve the problem quite well and are very close syntax we already have (if-expressions and switch-expressions).

1 Like

I don't think do expressions alone will get any traction unless it somehow gets separated from the multi-line-expression debate.

2 Likes

With respect, I think the repeated suggestions for do expressions in this thread is off topic. It's already been said that do expressions are a good idea:

do expressions are a good idea which deserve their own Swift pitch and proposal.

But I do not see how it eliminates the value or need of guard-let-catch and if-let-catch.

4 Likes