12th chapter. Properties

Source: Internet
Author: User

Source

Attributes are divided into computed properties, stored properties, type properties

In addition, you can define property monitors to monitor changes in property values. The property monitor can be added to a stored property that you write, or to a property that inherits from a parent class.

Store Properties

Simply put, a stored property is a constant or variable stored in an instance of a particular class or struct.

The following example defines a struct named Fixedlengthrange, which describes an interval in which the range width cannot be modified after creation:

struct Fixedlengthrange {     var  firstvalue:int     var range = Fixedlengthrange (firstvalue:0, length:3// // The interval now represents an integer 6,7,8, Because length is a constant property, it cannot be modified after that value. 

Constants and Storage properties
// If you create an instance of a struct and assign a value to a constant, you cannot modify any of the properties of the instance, even if the variable store property is defined:let range = Fixedlengthrange (firstvalue:0, Length:4  ////

This behavior is because the struct (struct) belongs to a value type. When an instance of a value type is declared as a constant, all its properties are also constants.

Classes that belong to reference types are different, and you can still modify the instance's variable properties after assigning an instance of a reference type to a constant.

Deferred Storage Propertiesa deferred store property is a property whose initial value is evaluated when it is first called. Use @lazy to mark a deferred storage property before the property declaration.

Note: The deferred storage attribute must be declared as a variable (using the var keyword) because the value of the property may not be available until the instance construction is complete.

class Dataimporter {/*Dataimporter is a class that imports data from external files.     Initialization of this class can take a lot of time. */     varFileName = "Data.txt"//This is the ability to provide data import} class DataManager {@lazyvarImporter =Dataimporter ()vardata =string[] ()//This is the ability to provide data management} let manager=DataManager () manager.data+ = "Some data"Manager.data+ = "Some More Data"//the importer attribute of the Dataimporter instance has not been created yet

Only the @lazy,importer attribute is created when it is first accessed. For example, when accessing its properties filename:

////

Calculated Properties

In addition to storing properties, classes, structs, and enumerations can define computed properties, calculated properties do not store values directly, but instead provide a getter to get the value, an optional setter to indirectly set the value of another property or variable.

struct Point {varx = 0.0, y = 0.0} struct Size {varwidth = 0.0, height = 0.0} struct Rect {varOrigin =Point ()//Store PropertyvarSize =Size ()//Storage PropertiesvarCenter:point {//calculate Property Get {Let CenterX= origin.x + (SIZE.WIDTH/2) Let CenterY= Origin.y + (SIZE.HEIGHT/2)returnPoint (X:centerx, Y:centery)} set (Newcenter) {origin.x= Newcenter.x-(SIZE.WIDTH/2) ORIGIN.Y= Newcenter.y-(SIZE.HEIGHT/2)   }
}}
convenient Set Declarationif the setter for the computed property does not define a parameter name that represents the new value, you can use the default name newvalue. The following is a rect struct code that uses the handy setter declaration:
struct Alternativerect {     var origin = Point ()     var size = size ()      var  center:point {     get {         = origin.x + (size.width/2)         = Origin.y + (s IZE.HEIGHT/2)           return point (X:centerx, y:centery)     }     set {         = NE Wvalue.x-(SIZE.WIDTH/2)         = newvalue.y-(SIZE.HEIGHT/2)     }     

read-only computed properties

Only a getter without a setter is a computed property that is a read-only computed property.

Note: You must use the var keyword to define calculated properties, including read-only computed properties, because their values are not fixed. The Let keyword is used only to declare a constant property, indicating a value that cannot be modified after initialization.

The declaration of a read-only computed property can be stripped of the Get keyword and braces:

struct Cuboid {     var width = 0.0, height = 0.0, depth = 0.0     var  volume:double {
    return width * Height * depth     = Cuboid (width:4.0, height:5.0, depth:2.0) println ( "\ (four.volume)"//

Does it have a write-only attribute?

Property Monitor

Attribute observers are divided into two types:

    • Willset (triggered before property value changes)-default namenewValue
    • Didset (triggered after property value changes)-default parameter name oldValue .

Note: willSet and didSet observers are not called during property initialization, they are called only when the value of the property is set outside of the initialization

class Stepcounter {    var totalsteps:int = 0 {        willset {            println ("About to Set Totalsteps to \ (newvalue)        }        didset {            if totalsteps > oldValue  {                println ("Added \ (totalsteps-oldvalue) steps")     }}}

Global variables and local variables
    • A global variable is a variable defined outside a function, method, closure, or any type
    • A local variable is a variable defined inside a function, method, or closure

Attention:

Global constants or variables are deferred, similar to deferred storage properties, except that global constants or variables do not require a tag lazy attribute.
Local-scope constants or variables do not delay calculations

class properties (equivalent to static properties)
    1. The definition class property is in the format of the class var property name: type {get/set {}}
    2. For reference types, a class property must use a computed property, not a stored property
    3. The class property must be defined as a variable type because the Class property is a calculation type and the calculation type must be a variable
    4. You must set a default value for the Class property because the class attribute is not part of the instance and cannot be assigned with any constructor
type attribute Syntax
struct Somestructure {//struct-body staticvarStoredtypeproperty = "Some value."StaticvarComputedtypeproperty:int {//This returns an INT value}} enum someenumeration {//enum staticvarStoredtypeproperty = "Some value."StaticvarComputedtypeproperty:int {//This returns an INT value}} class SomeClass {//ClassvarComputedtypeproperty:int {//This returns an INT value    } } 

Note: The computed Type property in the example is read-only, but you can also define a readable writable type property

Gets and sets the value of the Type property, accessed directly through the class name:

// somestructure.storedtypeproperty = "another value."    //

Type attribute in struct:

struct Audiochannel {static let Thresholdlevel= 10StaticvarMaxinputlevelforallchannels = 0varCurrentlevel:int = 0{didset {ifCurrentLevel >Audiochannel.thresholdlevel {//set the new level value to the thresholdCurrentLevel =Audiochannel.thresholdlevel}ifCurrentLevel >Audiochannel.maxinputlevelforallchannels {//stores the current level value as the new maximum input levelAudiochannel.maxinputlevelforallchannels =CurrentLevel}
The function of this code is to control the value of the CurrentLevel not exceeding Ten }}}
Rightchannel.currentlevel =  println (rightchannel.currentlevel)  //  Output "Ten"   println (audiochannel.maxinputlevelforallchannels)  //  Output "Ten"  

2015-03-21

19:44:13

12th chapter. Properties

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.