class 属性 getter/setter 的正确生产实施

Proper production implementation of class property getter/setter

在Java、PHP、Swift等语言中,分别有this$thisself等关键字,它们是指向包含 class 的特定实例的自反指针。如果没有其他局部变量共享相同的标识符,Java 和 Swift 都允许程序员完全省略该语句。我的问题是在生产中推荐的写法是什么?例如,生产中的程序员可以在不需要时省略 self 吗?

var name: String = ""

init(name: String) {
    self.name = name
}

func doSomeMethod() {
    print(name)
}

或者生产中的开发人员 总是 在访问实例属性时通常使用 self 子句,例如

var name: String = ""

init(name: String) {
    self.name = name
}

func doSomeMethod() {
    print(self.name)
}

文档描述的很好

The self Property

Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self property to refer to the current instance within its own instance methods.

The increment() method in the example above (see the example in the linked guide) could have been written like this:

func increment() {
  self.count += 1 
} 

In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. This assumption is demonstrated by the use of count (rather than self.count) inside the three instance methods for Counter. (Counter is a class mentioned in the section).

The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the self property to distinguish between the parameter name and the property name.

来源:The Swift Language Guide: Methods

我非常喜欢在生产代码中始终使用 this

它对发出的机器代码没有影响,让程序员的事情变得更容易,而不是让事情变得更容易,这对多样性来说毫无意义 您可能想要使用的其他工具。 (即代码搜索工具、lint 类工具等)

此外,避免愚蠢的拼写错误所节省的时间比打字节省的时间要多得多。

当前有一个 proposal on the swift-evolution repository 在访问实例属性时要求 self。它为始终需要它提供了一个相当有说服力的论据。