The declaration and function of properties in Swift
1. Introduction
Attributes associate values with classes, structures, and enumerations. Properties in Swift are divided into two types: stored properties and computed properties. Stored properties are used to store a value and can only be used for classes and structures. Computed properties are used to calculate a value and can be used for classes, structures and enumerations. Lift.
2. Storage attributes
Storage attributes use variables or constants to store a value. When declaring a storage attribute, you can set a default value for it, or you can The construction example is to set the value. The attributes can be accessed through dot syntax. The sample code for the storage attribute of the structure is as follows:
struct MyStruct { var property1 = 1 var property2:Int } var obj = MyStruct(property1: 1, property2: 2) //通过点语法进行属性的访问 print(obj.property1,obj.property2)
The above structure, if there is If a property is declared as a let constant, the property cannot be modified. Another thing to note is that if you use let when creating an instance of a structure, the properties in the structure cannot be modified even if they are variables. This is very different from classes.
There is also a type of storage attribute called delayed storage attribute. You can imagine a situation where some attributes of a class may not be used after every instance of the class, and the construction of some attributes may consume A lot of time, a smart design at this time is that when the class is instantiated, this type of attribute is not constructed. When an instance of the subclass uses this attribute, this attribute is constructed. Such an attribute is It is called a delayed storage attribute and is declared using the lazy keyword. The example is as follows:
//第一个类 class MyClass1 { init(){ print("MyClass1类被构造") } } class MyClass2 { //声明为延时存储属性 lazy var body = MyClass1() } //在构造MyClass2时 并不会进行body属性的构造 不会有打印信息 var obj2 = MyClass2() //执行下面代码后 会有打印信息 使用body属性使得body被构造 obj2.body
Note that if the delayed construction attribute is executed in multiple threads Use, there is no guarantee that it will be constructed only once.
3. Calculated properties
A simple understanding is that calculated properties are not independent properties used to store values. Developers can even understand them as a calculation method. , which is mainly used to obtain or set the value of other stored properties through calculation. An example is as follows:
struct Circle { //圆心 var center:(Double,Double) //半径 var r:Double //周长 将其作为计算属性 var l:Double{ get{ //计算圆的周长 return 2.0*r*M_PI } set{ //通过周长重新计算半径 默认传入的参数名为newValue r = newValue/(M_PI*2) } } } var circle = Circle(center: (0,0), r: 2) print(circle.l) circle.l=24 print(circle.r)
As you can see from the above demonstration code, the l attribute is not a new attribute, but l is calculated through the r attribute, or through l to deduct r. One thing to note is that two code blocks, set and get, can be created in the calculated attribute. The set code block is optional, and a newValue parameter will be generated by default to pass the data passed in from the outside. The get code The block must be implemented. Of course, you can also only implement the get code block. In this case, this property will be a read-only calculated property that can only be obtained and cannot be set. Another thing to note is that developers can also customize a parameter name after the set code block to receive parameters passed in from the outside. The example is as follows:
struct Circle { //圆心 var center:(Double,Double) //半径 var r:Double //周长 将其作为计算属性 var l:Double{ get{ //计算圆的周长 return 2.0*r*M_PI } set(newL){ //通过周长重新计算半径 默认传入的参数名为newValue r = newL/(M_PI*2) } } }
Read-only calculated properties can be further abbreviated. Because there is no set code block, the keyword get and parentheses can also be omitted without causing ambiguity. The example is as follows:
struct Point { var x:Double var y:Double var center:(Double,Double){ return (x/2,y/2) } }
4. Property listener
The get and set methods in the calculated properties in Swift and the get and set methods in Objective-C are actually not the same. Yes, Objective-C provides set and get methods that allow developers to perform some customized operations when properties are about to be obtained or set. This part of the development needs are implemented in Swift through property listeners.
There are two types of attribute listeners, willSet and didSet. willSet is executed when the attribute value is about to change, and didSet is executed when the attribute value has changed, and the values before and after the change are passed in. An example is as follows:
struct Point { var x:Double var y:Double{ willSet{ print("将要进行值的更新设置,新的值是:",newValue) } didSet{ print("已经进行值得更新设置,旧的值是:",oldValue) } } var center:(Double,Double){ return (x/2,y/2) } } var point = Point(x: 3, y: 3) //将打印 /* 将要进行值的更新设置,新的值是: 4.0 已经进行值得更新设置,旧的值是: 3.0 */ point.y=4
willSet will generate a parameter named newValue by default, and didSet will generate a parameter named oldValue by default, which can also be customized. The naming of these parameters, examples are as follows:
struct Point { var x:Double var y:Double{ willSet(new){ print("将要进行值的更新设置,新的值是:",new) } didSet(old){ print("已经进行值得更新设置,旧的值是:",old) } } var center:(Double,Double){ return (x/2,y/2) } }
5. Instance attributes and type attributes
Instance attributes are for With an instance of a type, type attributes refer directly to the type. Every time a pair of types is instantiated, its instance has an independent set of instance properties, and the type properties are shared by all instances of the class. In Objective-C, global properties are usually used to achieve this effect. In Swift , use the static keyword to declare type attributes. The example is as follows:
struct Point { //类型存储属性 static var name:String = "Point" //类型计算属性 static var subName:String{ return "sub"+name } var x:Double var y:Double{ willSet(new){ print("将要进行值的更新设置,新的值是:",new) } didSet(old){ print("已经进行值得更新设置,旧的值是:",old) } } var center:(Double,Double){ return (x/2,y/2) } } //类型属性 通过类型点语法来获取 print(Point.name,Point.subName)
Note that there is a special case for calculating attributes for the type of a class. If It requires inheritance and rewriting by subclasses, and the static keyword needs to be replaced by the class keyword. The example is as follows:
class SomeClass { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 27 } //支持子类进行重写的计算属性 class var overrideableComputedTypeProperty: Int { return 107 } }
For more articles related to the declaration and function of attributes in Swift, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











According to news on July 31, Apple issued a press release yesterday (July 30), announcing the launch of a new open source Swift package (swift-homomorphic-encryption) for enabling homomorphic encryption in the Swift programming language. Note: Homomorphic Encryption (HE) refers to an encryption algorithm that satisfies the homomorphic operation properties of ciphertext. That is, after the data is homomorphically encrypted, specific calculations are performed on the ciphertext, and the obtained ciphertext calculation results are processed at the same time. The plaintext after state decryption is equivalent to directly performing the same calculation on the plaintext data, achieving the "invisibility" of the data. Homomorphic encryption technology can calculate encrypted data without leaking the underlying unencrypted data to the operation process.

TogetintliteralattributeinsteadofSyntaxError,useaspaceorparenthesis.TheintliteralisapartifNumericLiteralsinPython.NumericLiteralsalsoincludesthefollowingfourdifferentnumericaltypes−int(signedintegers)−Theyareoftencalledjustintegersorints,arepositiveo

How to implement data import and export functions in Swift using MySQL Importing and exporting data is one of the common functions in many applications. This article will show how to use MySQL database to import and export data in Swift language, and provide code examples. To use the MySQL database, you first need to introduce the corresponding library files into the Swift project. You can do this by adding the following dependencies in the Package.swift file: dependencies:[

The Gson@SerializedName annotation can be serialized to JSON and have the provided name value as its field name. This annotation can override any FieldNamingPolicy, including the default field naming policy that may have been set on the Gson instance. Different naming strategies can be set using the GsonBuilder class. Syntax@Retention(value=RUNTIME)@Target(value={FIELD,METHOD})public@interfaceSerializedNameExample importcom.google.gson.annotations.*;

Vue.js is a popular JavaScript framework for building user interfaces. The Swift language is a programming language used for iOS and macOS application development. In this article, I will explore how to integrate Vue.js with the Swift language for advanced iOS application development and testing. Before we get started, we need to make sure you have the following software and tools installed: Xcode: an integrated development environment for developing and compiling iOS applications. Node.js: used for

Python's dir() function: View an object's properties and methods, specific code example required Summary: Python is a powerful and flexible programming language, and its built-in functions and tools provide developers with many convenient features. One of the very useful functions is the dir() function, which allows us to view the properties and methods of an object. This article will introduce the usage of the dir() function and demonstrate its functions and uses through specific code examples. Text: Python’s dir() function is a built-in function.

Thread of Despair is a rare card in Blizzard Entertainment's masterpiece "Hearthstone" and has a chance to be obtained in the "Wizbane's Workshop" card pack. Can consume 100/400 arcane dust points to synthesize the normal/gold version. Introduction to the attributes of Hearthstone's Thread of Despair: It can be obtained in Wizbane's workshop card pack with a chance, or it can also be synthesized through arcane dust. Rarity: Rare Type: Spell Class: Death Knight Mana: 1 Effect: Gives all minions a Deathrattle: Deals 1 damage to all minions

How to develop real-time chat function using Redis and Swift Introduction: Real-time chat function has become an indispensable part of modern social applications. When developing social applications, we often need to use real-time chat to provide interaction and information exchange between users. In order to meet the requirements of real-time and high availability, we can use Redis and Swift to develop such a function. Introduction to Redis: Redis is an open source in-memory data structure storage system, also known as a data structure server. It provides multiple
