Home > Backend Development > Python Tutorial > The declaration and function of properties in Swift

The declaration and function of properties in Swift

高洛峰
Release: 2017-03-01 13:37:33
Original
1327 people have browsed it

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)
Copy after login

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
Copy after login

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)
Copy after login

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)
    }
  }
}
Copy after login

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)
  }
}
Copy after login

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
Copy after login

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)
  }
}
Copy after login

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)
Copy after login

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
  }
}
Copy after login


For more articles related to the declaration and function of attributes in Swift, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template