Swift Properties
Swift properties associate values with a particular class, structure, or enumeration.
Properties can be divided into stored properties and computed properties:
| Stored Properties | Computed Properties |
|---|---|
| Store constants or variables as part of an instance | Compute (rather than store) a value |
| Used for classes and structures | Used for classes, structures, and enumerations |
Stored and computed properties are usually used for instances of a particular type.
Properties can also be used directly on the type itself, and such properties are called type properties.
Additionally, you can define property observers to monitor changes in property values, thereby triggering a custom action. Property observers can be added to stored properties you write, or to properties inherited from a superclass.
Stored Properties
In simple terms, a stored property is a constant or variable stored in an instance of a particular class or structure.
Stored properties can be variable stored properties (defined with the `var` keyword) or constant stored properties (defined with the `let` keyword).
You can specify a default value when defining a stored property.
You can also set or modify the value of a stored property during initialization, and even modify the value of a constant stored property.
import Cocoa
struct Number
{
var digits: Int
let pi = 3.1415
}
var n = Number(digits: 12345)
n.digits = 67
print("\(n.digits)")
print("\(n.pi)")
The output of the above program is:
67 3.1415
Consider the following code:
let pi = 3.1415
In the code, `pi` is given a default value when the stored property is defined (`pi = 3.1415`), so no matter when you instantiate the structure, it will not change.
If you define a constant stored property and try to modify it, an error will be reported, as shown below:
import Cocoa
struct Number
{
var digits: Int
let numbers = 3.1415
}
var n = Number(digits: 12345)
n.digits = 67
print("\(n.digits)")
print("\(n.numbers)")
n.numbers = 8.7
The above program will report an error when executed, as shown below:
error: cannot assign to property: 'numbers' is a 'let' constant n.numbers = 8.7
It means 'numbers' is a constant, and you cannot modify it.
Lazy Stored Properties
A lazy stored property is a property whose initial value is not calculated until it is first accessed.
Use before the property declarationlazyto indicate a lazy stored property.
Note:
You must declare a lazy stored property as a variable (usingvarkeyword), because the value of the property may not be obtained before the instance initialization is complete. Constant properties must have an initial value before initialization completes, so they cannot be declared as lazy properties.
Lazy stored properties are generally used for:
Delaying the creation of objects.
When the property's value depends on other unknown classes.
import Cocoa
class sample {
lazy var no = number() // `var` 关键字是必须的
}
class number {
var name = "Example Swift 教程"
}
var firstsample = sample()
print(firstsample.no.name)
The output of the above program is:
Example Swift 教程
Instance Variables
If you have experience with Objective-C, you should know that Objective-C provides two ways to store values and references for class instances. For properties, instance variables can also be used as the backing storage for property values.
The Swift programming language unifies these theories using properties. Properties in Swift do not have a corresponding instance variable, and the backing storage of a property cannot be accessed directly. This avoids the confusion of different access methods in different scenarios, and also simplifies the definition of a property into a single statement.
All the information about a property in a type—including its name, type, and memory-management characteristics—is defined in one single place (in the type definition).
Computed Properties
In addition to stored properties, classes, structures, and enumerations can definecomputed properties, computed properties do not directly store a value. Instead, they provide a getter to obtain a value and an optional setter to indirectly set the value of other properties or variables.
import Cocoa
class sample {
var no1 = 0.0, no2 = 0.0
var length = 300.0, breadth = 150.0
var middle: (Double, Double) {
get{
return (length / 2, breadth / 2)
}
set(axis){
no1 = axis.0 - (length / 2)
no2 = axis.1 - (breadth / 2)
}
}
}
var result = sample()
print(result.middle)
result.middle = (0.0, 10.0)
print(result.no1)
print(result.no2)
The output of the above program is:
(150.0, 75.0) -150.0 -65.0
If the setter of a computed property does not define a parameter name for the new value, you can use the default name `newValue`.
Read-Only Computed Properties
A computed property with only a getter and no setter is a read-only computed property.
A read-only computed property always returns a value; it can be accessed with the dot (.) operator, but cannot be set to a new value.
import Cocoa
class film {
var head = ""
var duration = 0.0
var metaInfo: [String:String] {
return [
"head": self.head,
"duration":"\(self.duration)"
]
}
}
var movie = film()
movie.head = "Swift 属性"
movie.duration = 3.09
print(movie.metaInfo["head"]!)
print(movie.metaInfo["duration"]!)
The output of the above program is:
Swift 属性 3.09
Note:
You must use
varkeyword to define computed properties, including read-only computed properties, because their values are not fixed.letThe keyword is only used to declare constant properties, indicating a value that cannot be modified after initialization.
Property Observers
Property observers monitor and respond to changes in a property's value. They are called every time a property is set, even when the new value is the same as the current value.
You can add property observers to stored properties other than lazy stored properties, and you can also add property observers to inherited properties (including stored and computed properties) by overriding the property.
Note:
You do not need to add property observers to computed properties that cannot be overridden, because you can directly monitor and respond to value changes through the setter.
You can add one or all of the following observers to a property:
willSetcalled before the new value is setdidSetcalled immediately after the new value is set- The `willSet` and `didSet` observers are not called during the initialization of a property.
import Cocoa
class Samplepgm {
var counter: Int = 0{
willSet(newTotal){
print("计数器: \(newTotal)")
}
didSet{
if counter > oldValue {
print("新增数 \(counter - oldValue)")
}
}
}
}
let NewCounter = Samplepgm()
NewCounter.counter = 100
NewCounter.counter = 800
The output of the above program is:
计数器: 100 新增数 100 计数器: 800 新增数 700
Global and Local Variables
The patterns described for computed properties and property observers can also be used for global and local variables.
| Local Variables | Global Variables |
|---|---|
| Variables defined inside a function, method, or closure. | Variables defined outside functions, methods, closures, or any type. |
| Used to store and retrieve values. | Used to store and retrieve values. |
| Stored properties are used to get and set values. | Stored properties are used to get and set values. |
| Also used for computed properties. | Also used for computed properties. |
Type Properties
Type properties are written as part of the type definition, inside the outermost curly braces ({}) of the type.
Use the keyword `static` to define type properties for value types, and the keyword `class` to define type properties for classes.
struct Structname {
static var storedTypeProperty = " "
static var computedTypeProperty: Int {
// 这里返回一个 Int 值
}
}
enum Enumname {
static var storedTypeProperty = " "
static var computedTypeProperty: Int {
// 这里返回一个 Int 值
}
}
class Classname {
class var computedTypeProperty: Int {
// 这里返回一个 Int 值
}
}
Note:
The computed type properties in the example are read-only, but you can also define readable and writable computed type properties, similar to the syntax for instance computed properties.
Getting and Setting Type Property Values
Similar to instance properties, type properties are accessed using the dot operator (.). However, type properties are accessed and set through the type itself, not through an instance. For example:
import Cocoa
struct StudMarks {
static let markCount = 97
static var totalCount = 0
var InternalMarks: Int = 0 {
didSet {
if InternalMarks > StudMarks.markCount {
InternalMarks = StudMarks.markCount
}
if InternalMarks > StudMarks.totalCount {
StudMarks.totalCount = InternalMarks
}
}
}
}
var stud1Mark1 = StudMarks()
var stud1Mark2 = StudMarks()
stud1Mark1.InternalMarks = 98
print(stud1Mark1.InternalMarks)
stud1Mark2.InternalMarks = 87
print(stud1Mark2.InternalMarks)
The output of the above program is:
97 87Other Extensions