self should be mandatory in Swift
| Originator: | robnapier | ||
| Number: | rdar://17301343 | Date Originated: | 13-Jun-2014 09:18 AM |
| Status: | Resolved: | ||
| Product: | Swift SDK | Product Version: | |
| Classification: | Reproducible: |
Accessing an object's own properties and methods should require prefixing with "self." The current implicit addition of self makes code more difficult to understand and maintain.
When faced with a line of code like:
speed = speed + acceleration
It is very unclear that this line may involve up to three function calls, and that the value of speed after this executes may not equal speed+acceleration (consider the case of SpeedLimitedCar from The Swift Programming Guide).
If this were explicit:
self.speed = self.speed + acceleration
Then you would know that there may be implicit functions hiding in this statement.
Similarly, faced with a line like
sort(myElements)
It is very unclear whether this refers to the stdlib function sort, or to an implicit self.sort(). In the presence of subclasses, this can become even more confusing.
Method calls in ObjC have always required self, and best practice for accessing properties in ObjC is to use self. Swift should continue this practice.
<strike>In the initializer, self should not be allowed, since the initializer directly accesses properties and does not use accessors. This makes the difference between initializers and methods clear.</strike>
---
Amended: Having written more Swift code, I would amend this Radar to say that self. should be required in init() as well.
---
Some additional confusions that come when self is not required:
https://gist.github.com/rnapier/4213dc64206b17df6935
https://gist.github.com/rnapier/478465d1b15e95b98b42
It is very easy to create spooky action at a distance when methods call functions if self is not required to indicate methods. Since Swift encourages the use of extensions for implementing various kinds of functionality, it is even more likely that these kinds of collisions will occur, and as shown, sometimes with non-deterministic results depending on how things compile. Unlike method/extension conflicts, the compiler cannot easily detect method/function conflicts.
---
Updated radar to indicate a new syntax:
self.x should be equivalent to .x rather than just x. This would fit in with enum syntax and would clear up the ambiguity.
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!