Swift properties
Swift properties associate values with a specific class, structure, or enumeration.
Attributes can be divided into stored attributes and calculated attributes:
Stored attributes | Computed attributes |
---|---|
Store a constant or variable as part of the instance | Compute (rather than store) a value |
Use For classes and structures | For classes, structures and enumerations |
Stored properties and computed properties are generally used for instances of specific types.
Attributes can also be used directly on the type itself. This type of attribute is called a type attribute.
In addition, you can also define attribute observers to monitor changes in attribute values to trigger a custom operation. Property observers can be added to stored properties written by yourself, or to properties inherited from parent classes.
Stored properties
Simply put, a stored property is a constant or variable stored in an instance of a specific class or structure.
Stored attributes can be variable stored attributes (defined with the keyword var) or constant stored attributes (defined with the keyword let).
You can specify the default value when defining the stored attribute
You can also set or modify the value of the stored attribute during the construction process, or even modify it The value of the constant storage attribute
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 execution output of the above program is:
67 3.1415
Consider the following code:
let pi = 3.1415
In the code, pi is defining the storage attribute Specify the default value (pi = 3.1415), so no matter when you instantiate the struct, it will not change.
If you define a constant storage attribute, if you 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
When the above program is executed, an error will be reported, and the error will be as follows:
error: cannot assign to property: 'numbers' is a 'let' constant n.numbers = 8.7
means 'numbers' is a constant, you cannot modify it.
Delayed storage properties
Delayed storage properties refer to properties whose initial value is calculated when it is called for the first time.
Use lazy before the attribute declaration to indicate a lazy storage attribute.
Note:
Delayed storage properties must be declared as variables (using thevar
keyword) because the value of the property may not be available before instance construction is completed. Constant properties must have an initial value before the construction process is completed, so they cannot be declared as delayed properties.
Delayed storage properties are generally used for:
Delayed object creation.
When the value of an attribute depends on other unknown classes
import Cocoa class sample { lazy var no = number() // `var` 关键字是必须的 } class number { var name = "php Swift 教程" } var firstsample = sample() print(firstsample.no.name)
The output result of the execution of the above program is:
php Swift 教程
Instantiation Variables
If you have experience with Objective-C, you should know that Objective-C provides two methods for storing values and references for class instances. For properties, you can also use instance variables as backend storage for property values.
In the Swift programming language, these theories are unified and implemented using attributes. Properties in Swift do not have corresponding instance variables, and the backend storage of properties cannot be accessed directly. This avoids the trouble of access methods in different scenarios, and also simplifies the definition of attributes into one statement.
All information about the properties in a type—including naming, type, and memory management characteristics—is defined in a single place (in the type definition).
Computed properties
In addition to stored properties, classes, structures and enumerations can define Computed properties. Computed properties do not store values directly, but provide a getter. Gets the 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 execution output of the above program is:
(150.0, 75.0) -150.0 -65.0
If the setter of the calculated property does not define a parameter name representing the new value, the default name newValue can be used.
Read-only computed properties
Computed properties with only getters and no setters are read-only computed properties.
Read-only computed properties always return a value and can be accessed through the dot (.) operator, but a new value cannot be set.
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 execution output of the above program is:
Swift 属性 3.09
Note:
Must use the
var
keyword to define calculated properties, including read-only Computed properties because their values are not fixed.let
The keyword is only used to declare constant attributes, indicating values that cannot be modified after initialization.
Property Observer
Property Observer monitors and responds to changes in property values. The property observer is called every time a property is set to a value, even for new values. This is no exception when it is the same as the current value.
You can add property observers for other stored properties except delayed stored properties, and you can also add property observers for inherited properties (including stored properties and calculated properties) by overloading properties.
Note:
There is no need to add property observers for computed properties that cannot be overloaded, because value changes can be directly monitored and responded to through setters.
You can add one or all of the following observers to the property:
willSet
Call before setting the new valuedidSet
Called immediately after the new value is setwillSet and didSet observers will not be called during property initialization Calling
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 above program execution output result is:
计数器: 100 新增数 100 计数器: 800 新增数 700
Global variables and local variables
Computed properties and property observers describe The pattern can also be used for global variables and local variables.
Local variables | Global variables |
---|---|
In Variables defined inside a function, method, or closure. | A function, method, closure, or variable defined outside of any type. |
is used to store and retrieve values. | is used to store and retrieve values. |
Stored properties are used to get and set values. | Stored properties are used to get and set values. |
is also used for computed properties. | is also used for computed properties. |
Type attributes
Type attributes are written as part of the type definition within the outermost curly braces ({}) of the type.
Use the keyword static to define type attributes of value types, and the keyword class to define type attributes 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 of instance computed properties.
Getting and setting the value of type attributes
Similar to instance attributes, type attributes are also accessed through the dot operator (.). However, type properties are obtained and set through the type itself, not through the instance. The example is as follows:
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 result of the execution of the above program is:
97 87