[swift-evolution] guard let x = x

Matthew Johnson matthew at anandabits.com
Wed Nov 2 16:02:36 CDT 2016


> On Nov 2, 2016, at 3:47 PM, Sean Heber via swift-evolution <swift-evolution at swift.org> wrote:
> 
> For what it’s worth, I concur. I think type narrowing makes it feel more like the language is actually doing some work *for* me rather than me having to babysit the language with some new syntax or keyword.

I’ve been staying out of the discussion because it doesn’t seem particularly relevant to Swift 4 phase 1, but +1.  Type narrowing is by far the most general and scalable solution which could be applied in other ways in the future.

> 
> l8r
> Sean
> 
> 
>> On Nov 2, 2016, at 3:25 PM, Haravikk via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> I still think that type narrowing is the right way to handle this like so:
>> 
>> 	if x != nil {
>> 		// x is definitely not nil inside this block (implicitly unwrapped)
>> 	} // x remains optional outside of it
>> 
>> 	if (x != nil) || (x == y) {
>> 		// if y's type is non-optional, then x is definitely not nil inside this block also
>> 		// i.e- if all conditions narrow to the same result, the type is narrowed inside the block
>> 	}
>> 
>> 	if x is Foo {
>> 		x.someMethodSpecificToFoo()
>> 	}
>> 
>> Personally I'm very much against the use of shadowing in the first place, and never use it myself. I tend to precede unwrapped value with "this" like so:
>> 
>> 	if let thisFoo = foo {
>> 		// Do something with thisFoo
>> 	}
>> 
>> I know it's maybe down to personal preference but I'd prefer to discourage shadowing entirely, and focus on type-narrowing, as it's a much more natural, and more generally useful, way to handle this "problem", as it doesn't actually require a specific syntax at all; if your condition narrows the type, then you can use the variable as whatever it is known to be.
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> _______________________________________________
> 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