Optional Return

I don't know if this idea has surfaced before, but I've found myself doing this way too often:

func foo(_ value: Int?) -> Int {
    if let value = value {
        return value
    // Do something else...

I wonder, if this syntax sugar is something that Swift would benefit from:

func foo(_ value: Int?) -> Int {
    return? value
    // Do something else...

The return? statement takes an expression of type R? where R is the return type of the enclosing function and returns if and only if the expression is not nil.

This would be particularly useful in combination with optional chaining:

func foo(_ value: Int?) -> String {
    return? value.map { "\($0)" }
    // Do something else...

What do you guys think?

1 Like

Implicit control flow around return seems like a great source of bugs. Remember gotofail.


I‘ve never used nor seen this pattern before. I don‘t consider that as a valid motivation for opposition, but afaics, you can easily avoid the boilerplate:

let fooResult = optionalValue ?? foo()

What‘s wrong with doing it this way?

Yet it does: SE-0231 — Optional iteration :wink:

Terms of Service

Privacy Policy

Cookie Policy