Declaration and action of attributes in Swift

Source: Internet
Author: User
First, Introduction

Property associates a value with a class, struct, enumeration. The properties in Swift are divided into storage properties and computed properties, which are used to store a value that can only be used for classes and structs, and computed properties are used to calculate a value that can be used for classes, structs, and enumerations.

Second, storage properties

Storage properties use variables or constants to store a value that can be set to a default value when declaring a stored property, or in a construction example where the value is set, the property can be accessed through the point syntax, and the sample code for the storage property of the struct is as follows:

struct MyStruct {  var property1 = 1  var property2:int}var obj = MyStruct (property1:1, Property2:2)//access to properties via point syntax Print (Obj.property1,obj.property2)

If an attribute is declared as a let constant, then this property cannot be modified. It is also important to note that if a let is used to create an instance of a struct, it cannot be modified even if the attribute in the struct is a variable. There is a big difference between this and the class.

There is also a class of storage properties called deferred storage properties, you can imagine that some of the properties of the class may not be used after each class instance, and some of the properties of the construction may consume a lot of time, a more intelligent design is when the class is instantiated, such properties are not constructed, This property is constructed when an instance of the secondary class is used to this property, which is called the deferred store property and is declared using the Lazy keyword, as shown in the following example:

First Class MyClass1 {  init () {    Print ("MyClass1 class is constructed")  }}class MyClass2 {  //declared as deferred store property  lazy var BODY = MyClass1 ()}//does not construct the Body property when constructing MyClass2 there will be no printing information var obj2 = MyClass2 ()//The following code will have printing information using the Body property to make the body constructed obj2.body

Note that if you use the deferred construction attribute in multiple threads, it is not guaranteed to be constructed only once.

Third, calculate the attribute

Simply understood, the computed attribute is not an independent property for storing values, and the developer can even interpret it as a computational method, which is primarily used to obtain or set the value of other stored properties by calculation. Examples are as follows:

struct Circle {  //center  VAR Center: (double,double)  //Radius  var r:double  //perimeter takes it as a calculated attribute  var l:d ouble{    get{      //Calculate the perimeter of a circle      return 2.0*r*m_pi    }    set{      //recalculate radius by perimeter default passed in parameter named NewValue      R = newvalue/(m_pi*2)    }  }}var circle = Circle (center: (0,0), r:2) print (CIRCLE.L) circle.l=24print (CIRCLE.R)

As you can see from the demo code above, the L property is not a new property, only the R attribute is calculated as L, or the R is reversed by L, and one of the things you need to note is that you can create two blocks of code in a computed attribute set and Get,set code blocks are optional, The default is to generate a newvalue parameter to pass the external data, get code block is necessary to implement, of course, can only implement a get code block, this property will be read-only computed properties, can only be obtained, cannot be set. It is also important to note that developers can also customize a parameter name after the set code block to receive incoming parameters, as shown in the following example:

struct Circle {  //center  VAR Center: (double,double)  //Radius  var r:double  //perimeter takes it as a calculated attribute  var l:double {    get{      //Calculate the perimeter of the Circle      return 2.0*R*M_PI    }    Set (NEWL) {      //recalculate radius by the perimeter the default passed in parameter named NewValue      r = newl/(M_pi*2)}}}  

Read-only computed properties can be shortened further, because there is no set code block, so the keyword get and parentheses can also be omitted, without ambiguity, the example is as follows:

struct Point {  var x:double  var y:double  var Center: (double,double) {    return (X/2,Y/2)  }}

Iv. Property Listener

The Get and set methods in the computed properties in swift and the Get and set methods in Objective-c are not really the same thing, Objective-c provides a set and get method that allows the developer to do some custom actions when the property is about to be fetched or set. This part of the development requirement is implemented in swift through a property listener.

The property listener has Willset and Didset two, Willset executes when the property value is about to change, didset when the value of the property has changed, and the value before and after the change is passed in. Examples are as follows:

struct Point {  var x:double  var y:double{    willset{      print ("Update setting to be updated, the new value is:", NewValue)    }    didset{      Print ("The old value is:", OldValue)    }  }  var center: (double,double) {    return (X/2,Y/2)  }} var point = Point (X:3, Y:3)//will print/* The update setting for the value to be made, the new value is: 4.0 has been made worth updating settings, the old value is: 3.0 */point.y=4

A parameter named NewValue is generated by default in Willset, and a parameter named OldValue is generated by default in Didset, and the names of these parameters can be customized, as shown in the following example:

struct Point {  var x:double  var y:double{    Willset (new) {      print ("Update setting for value will be set, the value is:"    Didset (old) {      print ("has been made worth updating settings, older values are:", "OID"    }  }  var center: (double,double) {    return (X/2,Y/2)  }}

V. Instance properties and Type properties

The instance property is for an instance of a type, and the type attribute is directly targeted with the type. Each pair of types is instantiated once, their instances have a set of independent instance properties, and the type attribute is common to all instances of the class, in Objective-c, the global properties are typically used to achieve this effect, and in swift, the static keyword is used to declare the Type property, as shown in the following example:

struct Point {  //Type store property  static var name:string = "point"  /Type calculation property  static var subname:string{    Return "sub" +name  }  var x:double  var y:double{    Willset (new) {      print ("The update setting for the value to be made, the value is:", New)    }    didset (old) {      print ("has been made worth updating settings, older values are:", "OID"    }  }  var center: (double,double) {    return (X/2,Y/2)  }} Type attribute gets print (point.name,point.subname) by type Point syntax

Note that there is a special case where a property is computed for the type of the class, and if it requires a subclass for inheritance rewriting, the static keyword needs to be replaced with the Class keyword, as shown in the following example:

Class SomeClass {  static var storedtypeproperty = "Some value."  static Var computedtypeproperty:int {    return)  //support subclass to override the computed property  class Var Overrideablecomputedtypeproperty:int {    return 107  }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.