In Swift, "self" should be mandatory for accessing instance members
| Originator: | alexisgallagher | ||
| Number: | rdar://17302742 | Date Originated: | 2014-06-13 |
| Status: | Open | Resolved: | |
| Product: | Swift SDK | Product Version: | Xcode6-Beta |
| Classification: | Reproducible: |
Summary:
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.
Consider a class like
class Foo {
var a:String = "Bob"
func printInfo(a:String) -> () {
println(a)
}
}
When looking at the line "println(a)" in isolation, it is not self-evident if I am accessing self.a or the local argument a, which shadows it.
Similarly, faced with a line like
sort(myElements)
It is 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.
In addition, I would suggest that explicit self is even *more* valuable in Swift than in ObjC, because Swift has many features which will make it more likely that people will define functions, variables, and constants in the top-level scope, outside of type definitions. I'm thinking of namespaces, its support for directly running .swift files, its REPL, and general support for functional programming idioms (where generic top-level functions typically act on objects, as opposed to being narrowly scoped as methods).
When people define more functions identifiers at the top-level, it becomes more crucial that code distinguish between top-level identifiers and type-scoped identifiers.
Steps to Reproduce:
1. define a type with a property and/or method
2. access the property and/or method
Expected Results:
3. I use a "self." prefix to access the property and/or method
Actual Results:
3. I can implicitly access the property and/or method
Version:
Xcode6-Beta
Notes:
Configuration:
always
Attachments:
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!