[swift-evolution] [Pitch] Computed properties as aliases
Harshil Shah
harshilshah1910 at me.com
Thu May 25 10:08:32 CDT 2017
Hi all,
The idea behind this is to add a shorter, cleaner syntax for the common pattern of using computed properties to provide public API for properties of private variables.
For example:
public var foo: Type {
get { return privateBar.baz }
set { privateBar.baz = newValue }
}
While this is a great improvement over the previous convention of `someVar:` and `setSomeVar:` as found in a lot of UIKit, it still has some issues.
It is overly verbose for the task at hand. It requires specifying the type of property that the variable is effectively acting as an alias for, stating the property name twice, and also doesn’t preclude the possibility of mistakenly using `privateBar.baz = foo` in the setter, which looks correct at a glance but just assigns the existing value of `baz` back to it, effectively doing nothing.
It could potentially be shortened, as follows:
public alias var foo = privateBar.baz
This new syntax omits additional type information which could be inferred from the type of the original variable, prevents any assignment mistakes in the setter, reduces the number of lines of code needed, and makes it clear that the purpose of the variable is simply to act as an alias.
I have used the `alias` keyword above as a placeholder. I suppose there might be needed some way to clarify that `foo` is still a computed property, and not a stored property declared as having the value of `privateBar.baz`. I realise that introducing a new keyword is not a trivial change, however this was simply the best idea I could come up with; I’m sure the community can find better solutions.
At the same time, a new keyword makes the intention of the variable explicit, and would break no Swift 3.* code.
I realise this is just syntactic sugar, however the pattern is common enough that I feel like it merits some discussion.
– Harshil
More information about the swift-evolution
mailing list