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

Patrick Smith pgwsmith at gmail.com
Sat May 14 00:56:12 CDT 2016


I’d probably write that as:

if let value = cachedValue { return value }

cachedValue = // … expensive calculation


> On 14 May 2016, at 3:52 PM, Karl via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 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
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution



More information about the swift-evolution mailing list