[swift-evolution] guard let x = x

Haravikk swift-evolution at haravikk.me
Wed Nov 2 15:25:23 CDT 2016


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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161102/b48505c9/attachment.html>


More information about the swift-evolution mailing list