在Swift WWDC会话介绍中,演示了只读属性description
:
class Vehicle {
var numberOfWheels = 0
var description: String {
return "\(numberOfWheels) wheels"
}
}
let vehicle = Vehicle()
println(vehicle.description)
Select 上述方法而不是使用一种方法是否有任何影响:
class Vehicle {
var numberOfWheels = 0
func description() -> String {
return "\(numberOfWheels) wheels"
}
}
let vehicle = Vehicle()
println(vehicle.description())
在我看来, Select 只读计算(computed)属性最明显的原因是:
-
Semantics-在本例中,
description
是类的属性,而不是它执行的操作是有意义的. - Brevity/Clarity-避免在获取值时使用空括号.
显然,上面的例子过于简单,但还有其他好的理由 Select 其中一个吗?例如,函数或属性是否有一些特性可以指导您决定使用哪个?
N.B. At first glance this seems like quite a common OOP question, but I'm keen to know of any Swift-specific features that would guide best practice when using this language.