[swift-evolution] Guard let

Vladimir.S svabox at gmail.com
Mon Jun 12 11:26:55 CDT 2017


On 10.06.2017 7:07, Justin Oroz via swift-evolution wrote:
> First time trying to contribute, hopefully this is the proper channel to submit.
> 
> I propose an addition to the guard let statement to allow for replacement of optionals with unwrapped values.
> 
> ex)
> 
> two current options
> 
> 
> obj.methodWithCallback() {(foo, bar) in
> 	guard let foo = foo else {
> 		return
> 	}
> 	
> 	foo.prop = “new”
> }
>   
> OR
> 
> obj.methodWithCallback() {(foo, bar) in
> 	guard foo != nil else {
> 		return
> 	}
> 	
> 	foo!.prop = “new”
> }
> 
> 
> I propose the following option:
> 
> obj.methodWithCallback() {(foo, bar) in
> 	guard foo else {
> 		return
> 	}
> 	
> 	foo.prop = “new”
> }
> 
> This reduces the seemingly redundant "guard let foo = foo” statement and removes the unnecessary forced optional unwrapping.
> 

There was a discussion about similar subject in the list and was decided IIRC that 
shadowing is not a good practice so it doesn't worth a special syntactic sugar. 
(correct me if I'm missing something)

Personally, I believe shadowing already (and will be) used very often(usually because 
we already have a good name for variable, and it is hard to invent one more) and 
*good* syntactic sugar for it will make Swift code more clean. But I like the 
suggestion with 'let' keyword for such shadowing to make it clear that 'foo' is 
shadowed(re-declared) with its unwrapped version :

obj.methodWithCallback() {(someMeaningfulName, bar) in
  	guard let someMeaningfulName else {
  		return
  	}
  	
  	someMeaningfulName.prop = “new”
}

Note that if it's 'foo' - it seems not a problem to write
guard let foo = foo else {..},
but when we have
guard let someMeaningfulName = someMeaningfulName else {..}
, we have to parse each variable to check if the same name declared or probably 
different name. Plus DRY principle.

if let someMeaningfulName {
   // unwrapped someMeaningfulName here
}

instead of

if let someMeaningfulName = someMeaningfulName {
}

> - Justin
> 
> 
> _______________________________________________
> 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