[swift-evolution] [Proposal] Type Narrowing

Haravikk swift-evolution at haravikk.me
Mon Nov 7 07:08:37 CST 2016


> On 7 Nov 2016, at 11:58, Charlie Monroe <charlie at charliemonroe.net> wrote:
> 
> I'd personally not make this automatic, but require explicit action from the developer.
> 
> In case of nullability, I have previously suggested "nonnil" keyword:
> 
> let foo: String? = "Hello World"
> guard nonnil foo else {
>     return
> }
> 
> In which way you explicitly request the type narrowing. Or:
> 
> let foo: Any
> guard foo as String else {
>     return
> }
> 
> I.e. not using "is" which returns a boolean, but using the cast operator, which IMHO makes more sense and prevents from unintentional type narrowing…

Normally I'm a proponent of being more rather than less explicit, but the biggest draw of type-narrowing to me is that you're *already* telling the type-checker, it's really just confirming what you know automatically.

So if I do:

	if foo is String {
		// Do lots of non-string stuff
		(foo as String).somethingStringSpecific
	}

On the last line of the block the type-checker is able to remind me that I already know that foo is a String, so I don't need to cast it.

Really when it comes down to it the type-narrowing never takes anything away from you; you can always handle the value as a less specific (wider) type if you want to, but if you want to treat it like a String because you know it's one, then you can do that too.

I'm concerned that if the feature had to be explicit, it would lack discoverability, and really the point is almost to get rid of the need to do things explicitly when you don't need to. It's like type inference on overdrive in a way.


I guess I just don't see why you'd think that "guard nonnil foo" is really more explicit than "guard foo != nil", in both cases you know that foo can't be nil past that point, so is a new keyword really justified?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161107/494ade16/attachment.html>


More information about the swift-evolution mailing list