[swift-evolution] [Proposal] Type Narrowing
Haravikk
swift-evolution at haravikk.me
Thu Nov 10 11:25:15 CST 2016
> On 10 Nov 2016, at 16:53, Jay Abbott <jay at abbott.me.uk> wrote:
>
> Haravikk,
>
> I think you missed ilya’s point with the owner/pet example:
>
> // This is inside the Owner class...
> func freeMyPetIfIHaveOne {
> if pet != nil {
> pet.setFree() // this sets pet = nil
> // self.pet is now nil - not due to concurrency, it was set to nil on this thread in the function above.
> // However, the compiler considers it a non-optional at this point
> pet.doStuff() // Compiler allows, bad things happen!
> }
> }
> As Dennis mentioned, narrowing only works for immutable values, and since optionals are always mutable it defeats the whole justification for it. I like the concept, but maybe it should be for immutables only?
>
If pet is of type Optional<T> then a .setFree() method on T cannot set self = nil, as self is of type T only in that scope.
The only way you can do something like that is to declare the setFree() method on Optional where Element:T, but that won't work on the updated proposal which uses a keyword to explicitly unwrap the variable (to avoid precisely that kind of Optional<T> vs T method conflict), you can view the updated proposals here:
https://github.com/Haravikk/swift-evolution/blob/master/proposals/NNNN-optional-unwrapping.md <https://github.com/Haravikk/swift-evolution/blob/master/proposals/NNNN-optional-unwrapping.md>
https://github.com/Haravikk/swift-evolution/blob/master/proposals/NNNN-type-narrowing.md <https://github.com/Haravikk/swift-evolution/blob/master/proposals/NNNN-type-narrowing.md>
I've also checked and a similar case like this for polymorphic types shouldn't be an issue either, as you can't assign self to a wider (or even orthogonal) type.
In other words, the only way that .setFree() can make changes that would break narrowing would be to have a reference to the instance you're working with, which is what the proposals now guard against. But for value types this should not be an issue at all.
This is all of course unless I'm missing something else, but I tried in a playground and I can't assign anything to self that would break narrowing/unwrapping that I can see, except through a reference type.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161110/eeeaabd8/attachment.html>
More information about the swift-evolution
mailing list