[Pitch] If let return

Many times I write:

if let foo {
    return foo
}

What about:

return if foo

drawing from other stylistic cousins like:

return try foo()
return await foo()

I searched discussions for this if let request and couldn't find anything. Forgive me if it exists somewhere already.

Could you say more about what you'd expect the behavior of that to be? The cousins you list always return from the function at that point (or exit in the case of the try version). Would return if foo return only if foo is non-nil? I think the if statement syntax makes that more clear, despite being longer.

4 Likes

I fear it will be extremely confusing to see:

return if foo
return someOtherFoo
2 Likes

Especially since you can already write:

return if let foo {
  foo
} else {
  someOtherFoo
}
1 Like

That last one could be just:

return foo ?? someOtherFoo

Re the pitch itself - no, I don't think it's 1. readable and 2. worth the trouble of optimising to begin with. We do not have precedents of other things like "throw ..." to conditionally do its thing.

5 Likes

I figured it might be a swiss-cheese idea and it turns out there are many holes. Thanks for the replies everyone

1 Like