[swift-evolution] Brainstorming: Optional sugar inferred map
Brent Royal-Gordon
brent at architechies.com
Tue Feb 16 17:49:04 CST 2016
> But wouldn’t you say optional chaining is almost the same thing? I’m a bit puzzled why people say this new proposal makes the code confusing, while the current implementation of optional chaining isn’t frowned upon.
My version is definitely completely analogous to optional chaining; you're just doing it on the optionality of the parameters instead of the method's target.
But just because it's analogous doesn't mean it's a good idea.
To see why, let's dispose of the "a" and "b" examples and do something a little more realistic. This code is based on something one of my controllers does (though I've intentionally complicated it). Give it a glance, but don't linger on it:
rebuildPageList(in: self.pagesPopupButton?.menu?, from: self.book?.tableOfContents.elements ?? [])
Does rebuildPageList(in:from:) get called every time this line is run? Does it depend on the popup button, the element list, or both? Which parts of the method chain that creates each parameter can be nil, and which cannot? If you carefully parse the line, you can answer all these questions, but it's not too easy at a glance.
This is less of a problem for the current optional chaining features because they all work in a line, so to speak; you can ignore the parameters and keys and merely focus on the chain of methods, properties, and subscriptors.
It's not that this isn't a straightforward extension of an existing idea—it absolutely is. But sometimes a syntax that's perfect for one area is too lightweight, too easy to overlook, for another. With this proposal in place, the only way to know if any function, or even any *operator*, is actually performed is to check all of its parameters for a question mark. That may be a bridge too far.
And again, I'm not convinced that there are *that* many cases where you want a function to return nil instead of being executed if one of its parameters is nil. It certainly happens sometimes—it's even happened to me on occasion—but I'm not sure it's a common enough case, particularly when the proposed solution is "add a feature that means the presence or absence of a single character buried in the middle of complex expression can make it conditional".
In short, your proposal will require people to read their code *much* more closely than they currently need to. I'm not sure it offers enough benefit to impose that cost.
--
Brent Royal-Gordon
Architechies
More information about the swift-evolution
mailing list