[swift-evolution] guard let x = x

Dany St-Amant dsa.mls at icloud.com
Tue Nov 1 20:47:15 CDT 2016


> Le 31 oct. 2016 à 17:44, Erica Sadun via swift-evolution <swift-evolution at swift.org> a écrit :
> 
> 
>> 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.

Also with the 'guard unwrap', the following code make sense:

guard unwrap x, x == 10 else { return }

With a lone unwrap it would not.

unwrap x, x == 10 else { return }

I personally do not like shadowing, but a standalone 'unwrap!' could be of interest to those loving life in the shadows. Beside the shadowing itself, it should not be any worst than any of the other '!' usage. The feasibility of such depends of course on how the compiler manages its variable scoping.

On further thought, if we were to make the, sorry bad word coming, code-breaking change to disallow legacy shadowing 'let x=x' and force the shadowing to be done exclusively via this 'unwrap' keyword, it could make it easier for projects/companies to ban shadowing.

Dany


More information about the swift-evolution mailing list