[swift-evolution] [Proposal] Type Narrowing

Haravikk swift-evolution at haravikk.me
Wed Nov 9 05:02:46 CST 2016


> On 9 Nov 2016, at 10:00, ilya <ilya.nikokoshev at gmail.com> wrote:
> 
> > What do you imagine being inside .complicatedStuff()? It shouldn't be possible for it to change foo to nil, as even if .complicatedStuff() reassigned this, it would be doing so as type T.
> 
> Why do you think so? All objects can be changed in any method. Let's rename foo to pet and complicatedStuff to setFree to give a specific example:
> 
> class Pet {
>     var owner: Person?
>     func setFree() 
>     {
>        // Maintain the relationship correctness.
>         owner?.pet = nil
>         owner = nil
>     }
> }
> 
> class Person { 
> 
> var pet: Pet? 
> 
> func ... {
>   if pet != nil {
>     pet.setFree() // this sets pet = nil
>     pet.setFree() // ???? what does this do ????
>     pet.setFree()
>   }
> }
> }

Ah, this comes back to the issue of class concurrency problems; the solution to this is that class references won't be narrowed, but the type-narrowing checks will still note cases that *could* have been narrowed, so that they can produce concurrency errors at runtime rather than the more generic error.

I just realised I never did provide a link to the working copy of the proposal, you can view some of the updates I've made here, which includes a note on classes and concurrency:
https://github.com/Haravikk/swift-evolution/blob/master/proposals/NNNN-type-narrowing.md

Though there is still a lot to do, especially if I'm going to have to change the proposal to use a keyword instead to avoid the Optional<T> to T method shadowing problem.

So yeah, in other words I'm assuming narrowing only on structs, as these are the only types where it is possible for the type-checker to be certain; though this could be extended to classes in future if we gain some attribute for indicating when they are "safe" (e.g- changed through copy-on-write, thus safe for narrowing).


More information about the swift-evolution mailing list