# Inferred return for guard statement

**URL:** <https://forums.swift.org/t/inferred-return-for-guard-statement/12099>\
**Category:** Pitches\
**Created:** [April 24, 2018, 8:20am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099 "2018-04-24T08:20:48Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![parski](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/parski/32/3013_2.png) [@parski](https://forums.swift.org/u/parski)\
**Post date:** [April 24, 2018, 8:20am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/1 "2018-04-24T08:20:48Z")

</div>

**Background**  
I'm very fond of the concept of early exits, breaking execution as early as possible to make sure the correct conditions are met before getting to the punchline. Swift encourages this concept by use of the `guard` statement and needless to say I use it abundantly. However, I find that most of the time I end the statement with `else { return }` or `else { return nil }`. I write this so often it feels like boiler plate that could be inferred.

**Pitch**  
If a function does not return a value or if it returns an optional, infer the `else` closure if omitted.

For example:

```swift
// Current
func voidFunction() {
    guard condition else { return }
    doTheThing()
}

func optionalFunction() -> SomeType? {
    guard let dependency = source else { return nil }
    return SomeType(with: dependency)
}

// Proposed inference
func voidFunction() {
    guard condition
    doTheThing()
}

func optionalFunction() -> SomeType? {
    guard let dependency = source
    return SomeType(with: dependency)
}

```

I think it would be easier to read and a lot nicer to work with. Should you want to use `throw`, `fatalError()` or any other way to break execution then the current syntax would still be available.

---

<div class="post-metadata">

**Author:** ![Tino](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tino/32/1073_2.png) [@Tino](https://forums.swift.org/u/Tino)\
**Post date:** [April 24, 2018, 8:37am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/2 "2018-04-24T08:37:58Z")

</div>

That could definitely save some keystrokes, and for `void` functions, it looks straightforward.  
But imho including `Optional`s blurs the picture:  
`nil` is a quite obvious choice, but wouldn't it also be natural if

```
func foo(arg: Int) -> [Int] {
   guard arg > 0
   // ....
}

```

would return an empty array?  
Afair, there are some languages whose handling of return value resembles `inout` variables, and with such a model, things like

```
func optionalFunction() -> SomeType? = nil {
    guard let dependency = source
    return SomeType(with: dependency)
}

```

feel quite natural.  
I'm just not sure if this would be a good fit for Swift.

---

<div class="post-metadata">

**Author:** ![parski](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/parski/32/3013_2.png) [@parski](https://forums.swift.org/u/parski)\
**Post date:** [April 24, 2018, 8:59am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/3 "2018-04-24T08:59:59Z")

</div>

I'll admit that void functions are a much better fit for inferred `else` closures and that Optionals might be too much magic for anyone learning the language but I still think it could apply for them. As for the `[Int]` example I do not propose any change to the current modus, but should all `else` closures be inferred I agree that the logical return value would be an empty `[Int]`. Again, I do not propose this.

---

<div class="post-metadata">

**Author:** ![nuclearace](https://avatars.discourse-cdn.com/v4/letter/n/51bf81/32.png) [@nuclearace](https://forums.swift.org/u/nuclearace)\
**Post date:** [April 24, 2018, 2:03pm UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/5 "2018-04-24T14:03:04Z")

</div>

I've always been a big skeptic of `guard`; it took me a while to really grok it. And I've also thought about whether something like a shortcut guard like this would be a good fit and my thoughts have usually come down to `guard condition` is not much better than writing the rest out.

---

<div class="post-metadata">

**Author:** ![nuclearace](https://avatars.discourse-cdn.com/v4/letter/n/51bf81/32.png) [@nuclearace](https://forums.swift.org/u/nuclearace)\
**Post date:** [April 24, 2018, 2:05pm UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/6 "2018-04-24T14:05:21Z")

</div>

That's an interesting idea, but like you say, I'm not so sure how good a fit that is for Swift. And IMO there's some other ergonomics with regards to functions that should probably be tackled first before this. Things like explicit partial-application syntax and the like.

---

<div class="post-metadata">

**Author:** ![parski](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/parski/32/3013_2.png) [@parski](https://forums.swift.org/u/parski)\
**Post date:** [April 24, 2018, 4:04pm UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/7 "2018-04-24T16:04:02Z")

</div>

I agree that it's not _much_ better but I do think it's better. I'm not proposing we make drastic changes to the language but to simply add the option to write clearer code by omitting boilerplate.

Consider the following function:

```swift
func aFunction(with optionalClosure: (() -> Void)? = nil) {
    guard let closure = optionalClosure else { return }
    closure()
}

```

When calling it:

```swift
// The closure can be omitted...
aFunction()

// ...or used in case you need it.
aFunction {
    doNecessaryThings()
}

```

I'm aware that `guard` is a statement and not a function but I'd argue that optional closures is a familiar concept to Swift users.

---

<div class="post-metadata">

**Author:** ![Jon\_Shier](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jon_shier/32/921_2.png) [@Jon\_Shier](https://forums.swift.org/u/Jon_Shier)\
**Post date:** [April 24, 2018, 4:28pm UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/8 "2018-04-24T16:28:55Z")

</div>

Just FYI, you don’t need `guard` at all in you example, as you can call optional closures directly. e.g. `optionalClosure?()`

---

<div class="post-metadata">

**Author:** ![reitzig](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/reitzig/32/2054_2.png) [@reitzig](https://forums.swift.org/u/reitzig)\
**Post date:** [April 24, 2018, 4:37pm UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/9 "2018-04-24T16:37:34Z")

</div>

What if the function throws? Do you want to set yourself up to silently swallow violated guards even though you wanted to throw an error?  
I appreciate the explicitness here; it forces me to specifically say "ignore this".

Also, in our production code we usually at least debug-log something when a guard (checking a precondition) fails. In asynchronous code we call the response handler (with an error value). Or we throw. That is to say, I'm not sure I've had `guard ... else { return }` very often, if at all.

---

<div class="post-metadata">

**Author:** ![Erica\_Sadun](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/erica_sadun/32/243_2.png) [@Erica\_Sadun](https://forums.swift.org/u/Erica_Sadun)\
**Post date:** [April 24, 2018, 4:51pm UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/10 "2018-04-24T16:51:21Z")

</div>

I like the clarity of explicit `return` and `return nil`. I'm not sure what's gained here and this covers only two cases: `F(...) -> Void` and `F(...) -> T?`.

An implementation of your pitch would be easier by changing `guard` to another word like `guardEarlyReturn` so it doesn't mess up parsing. But that makes it ugly.

I exclude `guard!`, which suggests `fatalError` and overlaps with `assert`/`precondition` and `guard?` which suggests only optional/nil returns.

---

<div class="post-metadata">

**Author:** ![benrimmington](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/benrimmington/32/695_2.png) [@benrimmington](https://forums.swift.org/u/benrimmington)\
**Post date:** [April 24, 2018, 5:21pm UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/11 "2018-04-24T17:21:35Z")

</div>

> [@\[Pitch\] Allow alternate version of 'Guard' with 'Guards'](https://forums.swift.org/t/pitch-allow-alternate-version-of-guard-with-guards/9049):
>
> Proposing an alternate of guard named guards that implicitly returns out of the function and would supply nil if an optional return was declared. This would be purely for the sake of brevity yet still allow for the more explicit guard version to be used. example: guard requiredObject != nil else { return } or guard requiredObject != nil else { return nil } becomes: guards requiredObject != nil but still allows for: guard requiredObject != nil else { // track analytic event or log case …

> [@An implicit return for guard](https://forums.swift.org/t/an-implicit-return-for-guard/3043):
>
> Dear community, While using ‘guard’ with much appreciation, I noticed a few cases where I would of hoped for better and more concise code. As of now, you receive a compiler error if your guard statement does not provide an ending statement such as return/break/etc. at the end. It is informative, but in many cases such a statement makes the code repetitive and less concise. As an example of cases where there are multiple guards done sequentially to avoid very nested and unclear ‘if's: gu…

> [@Guard Implicit Fallback](https://forums.swift.org/t/guard-implicit-fallback/1392):
>
> Hey everyone, I feel that `guard` could be a little more Swifty and would like to start a conversation concerning it. For example, I often have a function whose job depends on an optional having a value, and so I guard-let at the start and return if the guard fails. Or if the function returns an optional type, I'll simply return nil if guard fails. Can we improve on the general fallback case? Could we simply say: func noReturn() { &nbsp;&nbsp;&nbsp;&nbsp;guard let aValue = someOptional &nbsp;&nbsp;&nbsp;&nbsp;.... } and ha…

> [@Proposal: Add implicit/default else-behaviour for the guard statement](https://forums.swift.org/t/proposal-add-implicit-default-else-behaviour-for-the-guard-statement/558):
>
> I find myself writing the same else blocks for guard statements over and over again, so it might be reasonable to think about a default behaviour. In a current project I found 217 guard statements from which 183 have repetitive else clauses From which: 131 end with "else { return nil }" 44 "else { return }" 6 "else { continue }" 2 "else { break }" My proposal would be to make the else block optional and define a default behaviour. For example: func foo(x: Int) { ​ ​ guard x \< …

---

<div class="post-metadata">

**Author:** ![Chris\_Lattner3](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/chris_lattner3/32/348_2.png) [@Chris\_Lattner3](https://forums.swift.org/u/Chris_Lattner3)\
**Post date:** [April 25, 2018, 3:24am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/12 "2018-04-25T03:24:00Z")

</div>

Just MHO, but this feels like it favors terseness over clarity, which isn't the way that Swift typically balances.

---

<div class="post-metadata">

**Author:** ![parski](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/parski/32/3013_2.png) [@parski](https://forums.swift.org/u/parski)\
**Post date:** [April 25, 2018, 11:06am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/13 "2018-04-25T11:06:49Z")

</div>

@Jon_Shier I'm aware, the relevant part of my example is the optional closure.

@reitzig You can swallow unexpected errors with the current way of guard statement as well, albeit more explicitly so. You can still log using the closure but you don't always want to do so. I'm aware that Swift is not The iOS Language™ so forgive my for using a `UIKit` example but for instance the `UIView` function `layoutIfNeeded()` might not want to log anything should the layout not be needed.

```swift
func layoutIfNeeded() {
    guard needsLayout
    // layout
}

```

@Erica_Sadun I'm all for clarity, I just like the idea of the else clause being _optional_ as it often does nothing but returning.

Despite the list @benrimmington provided this idea does not seem to have made it to the list of common pitches I read prior to creating this thread. I take it this pitch is a popular opinion among quite a few of us.

---

<div class="post-metadata">

**Author:** ![dlbuckley](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dlbuckley/32/14986_2.png) [@dlbuckley](https://forums.swift.org/u/dlbuckley)\
**Post date:** [June 12, 2018, 9:46am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/14 "2018-06-12T09:46:22Z")

</div>

I was just been thinking about the removal of the `return` statement last night so did a little digging and came across this (and several other) topics.

The idea behind the removal of the guard scope entirely (as proposed above) is an interesting one, I quite like it personally. It acts kind of like a conditional `return` statement. But at the same time I can see where @Chris_Lattner3 is coming from in it possibly not being totally clear. But I think that it's not totally clear because it's not a common thing to do. If we think about it as a 'conditional return' like I mentioned earlier, then it becomes a lot more clear. But one could then argue that if it's going to act like a conditional return then it should possibly be named something entirely different like `escape` (I'm terrible at naming things, but hopefully you can see my point).

What originally brought me here was the thought of not needing the `return` within the scope of the guard if the containing method didn't contain a return type. For example:

```
// Currently
func myMethod() {
    guard true == true else {
        self.anotherMethod()
        return
    }
}

// Proposed
func myMethod() {
    guard true == true else {
        self.anotherMethod()
    }
}

```

With the proposed solution you would get the compiler warning `'guard' body must not fall through, consider using a 'return' or 'throw' to exit the scope`. We know a guard can't fall through, we know that the method doesn't throw or have a return type, so whats stopping the compiler from understanding that and implicitly returning instead of us having to explicitly state that it should return.

This is very much a small use case, but I feel like it's just one of those small rough edges in the language that could be smoothed out.

---

<div class="post-metadata">

**Author:** ![gwendal.roue](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/gwendal.roue/32/13992_2.png) [@gwendal.roue](https://forums.swift.org/u/gwendal.roue)\
**Post date:** [June 12, 2018, 9:57am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/15 "2018-06-12T09:57:18Z")

</div>

Hello Dale,

After such a change, what is this program supposed to print?

```swift
func dangerousGame() {
    for dice in [1, 2, 3, 4, 5, 6] {
        guard dice % 2 == 0 else { }
        print("Beetlejuice")
    }
}

```

---

<div class="post-metadata">

**Author:** ![gwendal.roue](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/gwendal.roue/32/13992_2.png) [@gwendal.roue](https://forums.swift.org/u/gwendal.roue)\
**Post date:** [June 12, 2018, 10:00am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/16 "2018-06-12T10:00:08Z")

</div>

This example is there to emphasize that program clarity takes profit from an explicit `return`, or `break`, or `continue`, etc.

---

<div class="post-metadata">

**Author:** ![dlbuckley](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dlbuckley/32/14986_2.png) [@dlbuckley](https://forums.swift.org/u/dlbuckley)\
**Post date:** [June 12, 2018, 10:08am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/17 "2018-06-12T10:08:09Z")

</div>

I hadn't considered that particular use case, but saying that I think it only makes sense to have an implicit return if it can be reasonably evaluated that one isn't needed. In your example there are several different options (`break` or `return`) so the compiler would require an explicit statement to understand what to do.

As a side note; I'm sure some people would look at the example not and go "don't use loops, did you not see the crusty talk at WWDC!" 😉

---

<div class="post-metadata">

**Author:** ![jeremyp](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jeremyp/32/3552_2.png) [@jeremyp](https://forums.swift.org/u/jeremyp)\
**Post date:** [June 12, 2018, 11:52am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/18 "2018-06-12T11:52:42Z")

</div>

> [@parski](#):
>
> but to simply add the option to write clearer code by omitting boilerplate.

It's not boilerplate and omitting it is not clearer.

There are several things you can do in the `else` block of a guard statement e.g. `break`, `fatalError`, `throw`. `return` is just one options and it is not clear to me why anybody would think it demands special treatment. For example in

```swift
for i in someSequece
{
    guard i < 5 else { ... }
    // do something
}

```

the most popular option is probably `break`.

It's clearer to be explicit about your intentions.

---

<div class="post-metadata">

**Author:** ![xwu](https://avatars.discourse-cdn.com/v4/letter/x/b487fb/32.png) [@xwu](https://forums.swift.org/u/xwu)\
**Post date:** [June 13, 2018, 1:48am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/19 "2018-06-13T01:48:53Z")

</div>

I wonder if this topic has been revisited a sufficient number of times that it might be worth considering as an addition to the list of [commonly rejected changes](https://github.com/apple/swift-evolution/blob/master/commonly_proposed.md).

---

<div class="post-metadata">

**Author:** ![rudkx](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/rudkx/32/20610_2.png) [@rudkx](https://forums.swift.org/u/rudkx)\
**Post date:** [June 13, 2018, 3:06am UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/20 "2018-06-13T03:06:48Z")

</div>

I think it probably merits inclusion. More generally I think any pitch that makes control-flow less explicit is a very hard sell.

---

<div class="post-metadata">

**Author:** ![Chris\_Lattner3](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/chris_lattner3/32/348_2.png) [@Chris\_Lattner3](https://forums.swift.org/u/Chris_Lattner3)\
**Post date:** [June 13, 2018, 4:43pm UTC](https://forums.swift.org/t/inferred-return-for-guard-statement/12099/21 "2018-06-13T16:43:34Z")

</div>

> [@xwu](#):
>
> I wonder if this topic has been revisited a sufficient number of times that it might be worth considering as an addition to the list of [commonly rejected changes](https://github.com/apple/swift-evolution/blob/master/commonly_proposed.md).

+1

-Chris
