[swift-evolution] guard let x = x

Haravikk swift-evolution at haravikk.me
Thu Nov 3 07:34:07 CDT 2016


> On 3 Nov 2016, at 08:17, Pyry Jahkola <pyry.jahkola at iki.fi> wrote:
> 
> As pleasing as it sounds*), the idea of type narrowing breaks down badly if:
> 
> – the binding is implicit (without explicit extra syntax involved) and
> – what is bound happens to be mutable.
> 
> An example being:
> 
>     // var message: String?
>     if message != nil { // magic turns 'message' into a non-optional 'String' here
>       handleMessage(message)
>       message = nil // 'String' is not 'ExpressibleByNilLiteral'
>     }
> 
> What magic would we require to still allow access to the Optional interface of 'message' in that block?

Type widening 😉

Basically if you try to assign a value to `message` that is not valid for the narrowed type, but is fine for a wider type then it can simply be widened again at that point. You could think of the variable's type as being a stack of types, each narrower than the last; if you hit a road-block with the current type, you can try rolling back (widening) until you find one that works, at which point this is the new narrowest type, or return an error as normal.

In this specific example you may instead think of it as re-narrowing, as after that line message can only be `nil`. 

In fact in that example we can look at it like this:

	// message is Optional
	if message != nil { // Optional.some
		handleMessage(message) // Optional.some
		message = nil // Optional.none
	} // Optional.none

As both branches ended with the same type, the type of message afterwards is Optional.none from that point on; allowing unwrapping operations to become invalid (as they cannot possibly succeed) and other useful behaviours. If message wasn't set to nil within the if statement then it would return to being the wider Optional (as it's the narrowest type that both branches have in common).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161103/8bfda06a/attachment.html>


More information about the swift-evolution mailing list