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

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

问题描述

在介绍 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 for choosing 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?

注意乍一看,这似乎是一个很常见的 OOP 问题,但我很想知道任何特定于 Swift 的功能可以指导使用这种语言时的最佳实践.

推荐答案

在我看来,这主要是风格问题:我非常喜欢使用 properties 来解决这个问题: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).

当 Apple 发布一些 Swift 编码约定时,我们可能会更加清楚.

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

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

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