Swift 中的计算只读属性与函数

在 Swift WWDC 会话介绍中,演示了一个只读属性 description:

class Vehicle {
var numberOfWheels = 0
var description: String {
return "\(numberOfWheels) wheels"
}
}


let vehicle = Vehicle()
println(vehicle.description)

选择上述方法而不是使用某种方法是否会产生任何影响:

class Vehicle {
var numberOfWheels = 0
func description() -> String {
return "\(numberOfWheels) wheels"
}
}


let vehicle = Vehicle()
println(vehicle.description())

在我看来,选择只读计算属性最明显的原因是:

  • 语义 -在这个例子中,description作为类的一个属性而不是它执行的一个操作是有意义的。
  • 简洁/Clarity -避免在获取值时使用空括号。

很明显,上面的例子过于简单,但是有没有其他好的理由选择其中一个而不是另一个呢?例如,是否有一些函数或属性的特性可以指导您决定使用哪些函数或属性?


注意。乍一看,这似乎是一个相当常见的 OOP 问题,但我渴望知道任何特定于 Swift 的特性,可以指导使用这种语言时的最佳实践。

32462 次浏览

Historically description is a property on NSObject and many would expect that it continues the same in Swift. Adding parens after it will only add confusion.

EDIT: After furious downvoting I have to clarify something - if it is accessed via dot syntax, it can be considered a property. It doesn't matter what's under the hood. You can't access usual methods with dot syntax.

Besides, calling this property did not require extra parens, like in the case of Swift, which may lead to confusion.

It seems to me that it's mostly a matter of style: I strongly prefer using properties for just that: properties; meaning simple values that you can get and/or set. I use functions (or methods) when actual work is being done. Maybe something has to be computed or read from disk or from a database: In this case I use a function, even when only a simple value is returned. That way I can easily see whether a call is cheap (properties) or possibly expensive (functions).

We will probably get more clarity when Apple publishes some Swift coding conventions.

Since the runtime is the same, this question applies to Objective-C as well. I'd say, with properties you get

  • a possibility of adding a setter in a subclass, making the property readwrite
  • an ability to use KVO/didSet for change notifications
  • more generally, you can pass property to methods that expect key paths, e.g. fetch request sorting

As for something specific to Swift, the only example I have is that you can use @lazy for a property.

There is a difference: If you use a property you can then eventually override it and make it read/write in a subclass.

While a question of computed properties vs methods in general is hard and subjective, currently there is one important argument in the Swift's case for preferring methods over properties. You can use methods in Swift as pure functions which is not true for properties (as of Swift 2.0 beta). This makes methods much more powerful and useful since they can participate in functional composition.

func fflat<A, R>(f: (A) -> () -> (R)) -> (A) -> (R) {
return { f($0)() }
}


func fnot<A>(f: (A) -> Bool) -> (A) -> (Bool) {
return { !f($0) }
}


extension String {
func isEmptyAsFunc() -> Bool {
return isEmpty
}
}


let strings = ["Hello", "", "world"]


strings.filter(fnot(fflat(String.isEmptyAsFunc)))

There are situations where you would prefer computed property over normal functions. Such as: returning the full name of an person. You already know the first name and the last name. So really the fullName property is a property not a function. In this case, it is computed property (because you can't set the full name, you can just extract it using the firstname and the lastname)

class Person{
let firstName: String
let lastName: String
init(firstName: String, lastName: String){
self.firstName = firstName
self.lastName = lastName
}
var fullName :String{
return firstName+" "+lastName
}
}
let william = Person(firstName: "William", lastName: "Kinaan")
william.fullName //William Kinaan

Well, you can apply Kotlin 's advices https://kotlinlang.org/docs/reference/coding-conventions.html#functions-vs-properties.

In some cases functions with no arguments might be interchangeable with read-only properties. Although the semantics are similar, there are some stylistic conventions on when to prefer one to another.

Prefer a property over a function when the underlying algorithm:

  • does not throw
  • complexity is cheap to calculate (or caсhed on the first run)
  • returns the same result over invocations

In the read-only case, a computed property should not be considered semantically equivalent to a method, even when they behave identically, because dropping the func declaration blurs the distinction between quantities that comprise the state of an instance and quantities that are merely functions of the state. You save typing () at the call site, but risk losing clarity in your code.

As a trivial example, consider the following vector type:

struct Vector {
let x, y: Double
func length() -> Double {
return sqrt(x*x + y*y)
}
}

By declaring the length as a method, it’s clear that it’s a function of the state, which depends only on x and y.

On the other hand, if you were to express length as a computed property

struct VectorWithLengthAsProperty {
let x, y: Double
var length: Double {
return sqrt(x*x + y*y)
}
}

then when you dot-tab-complete in your IDE on an instance of VectorWithLengthAsProperty, it would look as if x, y, length were properties on an equal footing, which is conceptually incorrect.

Semantically speaking, computed properties should be tightly coupled with the intrinsic state of the object - if other properties don't change, then querying the computed property at different times should give the same output (comparable via == or ===) - similar to calling a pure function on that object.

Methods on the other hand come out of the box with the assumption that we might not always get the same results, because Swift doesn't have a way to mark functions as pure. Also, methods in OOP are considered actions, which means that executing them might result in side effects. If the method has no side effects, then it can safely be converted to a computed property.

Note that both of the above statements are purely from a semantic perspective, as it might well happen for computed properties to have side effects that we don't expect, and methods to be pure.

From the performance perspective, there seems no difference. As you can see in the benchmark result.

gist

main.swift code snippet:

import Foundation


class MyClass {
var prop: Int {
return 88
}


func foo() -> Int {
return 88
}
}


func test(times: u_long) {
func testProp(times: u_long) -> TimeInterval {
let myClass = MyClass()
let starting = Date()
for _ in 0...times {
_ = myClass.prop
}
let ending = Date()
return ending.timeIntervalSince(starting)
}




func testFunc(times: u_long) -> TimeInterval {
let myClass = MyClass()
let starting = Date()
for _ in 0...times {
_ = myClass.prop
}
let ending = Date()
return ending.timeIntervalSince(starting)
}


print("prop: \(testProp(times: times))")
print("func: \(testFunc(times: times))")
}


test(times: 100000)
test(times: 1000000)
test(times: 10000000)
test(times: 100000000)

Output:

prop: 0.0380070209503174 func: 0.0350250005722046 prop: 0.371925950050354 func: 0.363085985183716 prop: 3.4023300409317 func: 3.38373708724976 prop: 33.5842199325562 func: 34.8433820009232 Program ended with exit code: 0

In Chart:

benchmark

An updated/fixed version of Benjamin Wen's answer incorporating Cristik's suggestion.

class MyClass { var prop: Int { return 88 }

    func foo() -> Int {
return 88
}
}


func test(times: u_long) {
func testProp(times: u_long) -> TimeInterval {
let myClass = MyClass()
let starting = CACurrentMediaTime()
for _ in 0...times {
_ = myClass.prop
}
let ending = CACurrentMediaTime()
return ending - starting
}


func testFunc(times: u_long) -> TimeInterval {
let myClass = MyClass()
let starting = CACurrentMediaTime()
for _ in 0...times {
_ = myClass.foo()
}
let ending = CACurrentMediaTime()
return ending - starting
}
    

print("prop: \(testProp(times: times))")
print("func: \(testFunc(times: times))")
}


test(times: 100000)
test(times: 1000000)
test(times: 10000000)
test(times: 100000000)