Syntactic sugar for simplifying guards

One very common pattern in swift is unwrapping of optionals in guard statements.

foo { [weak self] in
    guard let self = self else { return }
    self.bar()
}

I think it would be nice if we could shorten this like so:

foo { [weak self] in
    guard self else { return } // semantically same as above
    self.bar()
}

And in general compiler should be smart enough here to infer we have non-null as a result.

func foo(param: Bar?) {
    guard param else { return } // same as above example. let param = param
    param.bar()
}
3 Likes

What if it's an Optional<Bool>?

compiler warning/error due to ambiguity I think

Is there any precedent for ambiguity in choosing syntactic shortcuts?

In Swift 5.1 I believe we get a warning if you have an enum with case .none and you assign it to Optional value. It is not the same, but similar sort of ambiguity that compiler warns about.

In case of my idea compiler should have a special case for Bool give a warning that only identifier optional unwrapping is performed and no value comparison is made.

There have been a variety of pitches on this issue. You can search through the forums for these using keywords such as “guard unwrap”.

1 Like

Many posts and discussions around this topic made me realise that the reason we are using closures so much is all the completion APIs in Cocoa. Once we get proper asynchronous APIs in Swift (async/await) we can get rid of completion closures.

So ultimately the solution is not shorter weak selves, it’s async/await.

2 Likes