[swift-evolution] guard let x = x

David Goodine dmgoodine at gmail.com
Mon Oct 31 18:13:36 CDT 2016


One thing I really like that Erica mentioned in the earlier discussion is the case of guard unwrapping [weak self] in closures. I've taken to creating an alternate self (guard let ss = self else { return }) constant and using that. But it always felt inelegant. The proposed case works without falling prey to the protection against redefining self that the compiler still needs to enforce and does it in a way that's clear and concise.  

Sent from my iPhone

> On Oct 31, 2016, at 6:46 PM, William Sumner via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On Oct 31, 2016, at 3:44 PM, Erica Sadun via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> 
>>> On Oct 31, 2016, at 1:51 PM, Xiaodi Wu via swift-evolution <swift-evolution at swift.org> wrote:
>>> 
>>> An alternative that would seem to satisfy some objections is to have a distinct "unwrap" statement--as in: "unwrap x else { ... }".
>> 
>> I'd be against this alternative as it is doing the work of a guard statement (including the "must exit scope" rule) with a new keyword and unneeded redundancy.
>> 
>> Adding "unwrap" is local. It performs one very common task with added safety (avoids unintended shadow effects) and introduces succinctness and clarity. In other words, it is a highly focused changed with a measurable benefit in use.
>> 
>> Compare:
>> 
>> * "Introduce the unwrap statement that acts like guard but is limited to optionals" creates unnecessary language verbosity.
>> 
>> * "guard x else ", meaning "treat optional values differently than all other items in a conditional list", fails because it obscures rather than adds intent. Worse, it would lead to issues with Boolean optionals whose wrapped value is later used within the same condition.
>> 
>> Xiaodi, you mentioned an alternative approach and I'd love a peek at what that is.
>> 
>> — Erica
> 
> Your proposed form of unwrap naturally works in multiple places with clear readability:
> 
> var foo: Any?
> if unwrap foo {}
> 
> while unwrap foo {}
> 
> guard unwrap foo else { return }
> 
> Preston
> _______________________________________________
> 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