swift中的计算属性

Computed Properties
In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
计算属性
除了存储的属性,类,结构和枚举可以定义计算属性,实际上不存储值。相反,它们提供了一个getter和一个可选的setter来检索和间接设置其他属性和值。
因此:
1.计算属性它的设计目的并不是存储值,而是为了检索和间接设置其他属性。swift中的计算属性_第1张图片
便捷setter声明
If a computed property’s setter does not define a name for the new value to be set, a default name of newValue is used. Here’s an alternative version of the Rect structure, which takes advantage of this shorthand notation:
swift的计算属性可以简洁设置,即可以省略简写。默认就带一个newValue值。
swift中的计算属性_第2张图片
只读计算属性
A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.
一个拥有get但是没有set方法的属性。
swift中的计算属性_第3张图片
你必须声明计算属性包括只读计算属性,用var关键字。因为计算属性每次都在调用。
注意:
You can simplify the declaration of a read-only computed property by removing the get keyword and its braces:
你可以简单声明只读计算属性,通过移除get关键字和它的大括号。
swift中的计算属性_第4张图片

你可能感兴趣的:(swift,计算属性)