The motivation is pretty much the same as SE-0009
That is, we need a shorter form of self.property that is more readable at the point of use.
The idea is:
Add fallback lookup for identifier starts with single _
(ex. _name), if the identifier is not a local variable , member property or global variable, then treat it as self.(identifier without _
) (ex. self.name)
Suppose the identifier lookup can be simplified as:
closure / function
-> class / struct / enum member
-> global variable
The fallback lookup is added after global variable lookup
closure / function
-> class / struct / enum member
-> global variable
-> _ fallback lookup
This will avoid break existing source, and make this feature optional.
Additional restriction to the fallback lookup:
- it should apply to property only
- it should happen in the member function / constructor only
- it should apply to identifier starts with single
_
char (double or more_
should not trigger this lookup) - it should not apply to identifier that is explicitly bound (that is, with self. or instance.)
- compiler should issue warning if _identifier can be resolved as global variable and instance property at the same time
- optionally deprecate naming of property / global starts with single
_
private var _name: String = "Steve"
class Person {
var name: String = "David"
var title: String = "Manager"
var _phone: String?
func foo() {
print("Hello \(name)") // pickup self.name
print("Hello \(_name)") // pickup global _name (not fallback) , and compiler issue warning
print("Hello \(self.name)") // pickup self.name
print("Hello \(self._name)") // compile error
print("Hello \(_title)") // pickup self.title (fallback)
print("Hello \(_phone)") // pickup self._phone (not fallback)
}
}