Computed read-only property vs function in Swift

后端 未结 10 934
忘了有多久
忘了有多久 2020-12-04 11:00

In the Introduction to Swift WWDC session, a read-only property description is demonstrated:

class Vehicle {
    var numberOfWheels = 0
    var          


        
10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 11:02

    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.

提交回复
热议问题