[swift-evolution] [Idea] "guard not let" optional binding

Karl razielim at gmail.com
Sat May 14 00:52:17 CDT 2016


If we want to check that an optional has a value and bail if it doesn't, we have the helpful pattern:

    guard let x = x else { throw SomeError }

However, it is also fairly common that you want to check that an optional *is* nil, and still bail if it isn’t (maybe using the value that you now know exists), e.g:

    guard cachedValue == nil else { return cachedValue! }
    cachedValue = //… expensive calculation

It seems a little bit “unfair” that we have this lovely clean `let` syntax when checking for Optional.Some, but we to have to do this ugly manual check against nil and explicit unwrap when checking for Optional.None. There is literally no other way to satisfy the guard statement; our optional bindings only go one-way can’t be evaluated.

What about if we introduced a “not” modifier to optional bindings?

    guard not let cachedValue = _someExpensiveResult else { return cachedValue }

This obviously wouldn’t make sense for “if let…” switching, as the variables get bound in the ‘else’ block and the code wouldn’t be very readable. For the special case of a guard statement, though, which only has an ‘else’ block, it does make some sense.

If we had something like this, certainly in my code, I’d be able to eliminate almost all (maybe even all) remaining force-unwraps of optionals; that’s great! It’d be amazing if the language was expressive enough that you could go without ever having to force-unwrap an optional. And it just makes sense. 

Thoughts?

Karl


More information about the swift-evolution mailing list