Swift中计算的只读属性vs函数 [英] Computed read-only property vs function in Swift

查看:80
本文介绍了Swift中计算的只读属性vs函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

  • 语义-在此示例中,description作为类的属性而不是其执行的操作是有意义的.
  • 简洁/清晰-避免在获取值时需要使用空括号.
  • 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.乍一看,这似乎是一个非常普遍的OOP问题,但是我很想知道任何特定于Swift的功能,这些功能可以指导使用该语言时的最佳实践.

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.

推荐答案

在我看来,这主要是风格问题:我非常喜欢将 properties 用于:表示您可以获取和/或设置的简单值.在完成实际工作时,我会使用功能(或方法).也许必须从磁盘或数据库中计算或读取某些内容:在这种情况下,即使仅返回一个简单值,我也使用一个函数.这样一来,我可以轻松地看到一个呼叫是廉价的(属性)还是可能昂贵的(功能).

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).

当苹果发布一些Swift编码约定时,我们可能会变得更加清晰.

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

这篇关于Swift中计算的只读属性vs函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆