Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

methods - Computed read-only property vs function in Swift

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

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

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

Are there any implications to choosing the above approach over using a method instead:

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

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

It seems to me that the most obvious reasons you would choose a read-only computed property are:

  • Semantics - in this example it makes sense for description to be a property of the class, rather than an action it performs.
  • Brevity/Clarity - prevents the need to use empty parentheses when getting the value.

Clearly the above example is overly simple, but are there other good reasons to choose one over the other? For example, are there some features of functions or properties that would guide your decision of which to use?


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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...