Shorthand for guard else empty return statement

Hello,

most of the time I end up using the guard statement to simply do a return.

guard let url = URL(string:stringUrl) else {return}

I propose we allow a shorthand syntax on guard with an implicit empty return else statement.

guard let url = URL(string:stringUrl)

From the Swift Evolution common proposals document:

  • Infer return for omitted guard body: It has been proposed many times to allow omission of the guard body for the sake of brevity. However, a core principle of Swift is to make control flow explicit and visible. For example, the try keyword exists solely to indicate to the human reader where thrown errors can happen. Implicit returns would violate this principle, favoring terseness over clarity in a way that isn't typical of Swift. Furthermore, there are many ways of exiting the scope other than return (loops may want break or continue ), and not every function has an obvious default value to return.
17 Likes

Maybe then we could allow a shorter syntax such as

guard let url = URL(string:stringUrl) return
guard let url = URL(string:stringUrl) return nil
guard let url = URL(string:stringUrl) return [String]()
guard let url = URL(string:stringUrl) break

I would suggest reading existing discussions on this topic:

  1. An implicit return for guard
  2. Inferred return for guard statement
  3. Proposal: Add implicit/default else-behaviour for the guard statement
  4. Guard Implicit Fallback
  5. guard let x = x

Here's what Chris had to say about this:


Personally, I don't see the benefit of dropping curly braces, else or return (or a combination of them) - while you get rid of a few keystrokes, you lose a bit of clarity which isn't very nice.

1 Like