[swift-evolution] [Proposal] Type Narrowing
Haravikk
swift-evolution at haravikk.me
Mon Nov 7 05:34:31 CST 2016
> On 7 Nov 2016, at 03:52, Chris Lattner <clattner at apple.com> wrote:
> Introducing flow senstitive type refinement breaks this model because the type of a decl depends not just on its declaration, but on a potentially arbitrary number of imperative checks that occur between the declaration and the use. This can make it much more difficult to understand code.
This seems like more of a challenge for the IDE; if it can tap into the type-checker then it can determine what the narrowed type is at any given point in your code, indeed I would expect it to for the purposes of auto-completion anyway. I know you don't necessarily want a language that's reliant on good IDE support, but if you're doing something complex enough where this would become a problem and NOT using a good IDE then it seems kind of like a self-inflicted problem to me.
Even so there's nothing in this feature that would prevent you from using shadowing if you want to, for example if a block is especially large and you feel it adds clarity.
Actually though I'd say that for maintenance narrowing may be better, as it can clarify what a type is supposed to be at a given point, and if you break the narrowing then you'll create errors and warning that show you how you've changed the meaning of the code. Consider for example:
func doSomething(value:Int?) {
if (value == nil) { value = 5 } // value is narrow to Optional<Int>.some
// Lots of really important code that never causes value to become nil
print(value!.description)
}
Say you come back later and decide to remove the conditional at the top, now that value!, though a fair assumption at the time, can cause a runtime failure. With narrowing however you wouldn't have had to force unwrap because of the known non-nil value, but your change will break that, resulting in an error that forces you to fix it.
I'm still struggling how best to phrase my motivation section; so far I seem to have an increasingly large grab-bag of individual problems that type-narrowing can solve, with no way to put it more succinctly.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161107/cc5fc5ba/attachment.html>
More information about the swift-evolution
mailing list