Latest web development tutorials

Swift property

Swift property value with a specific class, structure, or enumeration association.

Property can be divided into storage properties and calculated properties:

Store PropertiesCalculation Properties
As an example of constant or variable storage part Calculated (rather than storing) a value
For classes and structures For classes, structures, and enumerations

Storage properties and properties are generally used to calculate the instances of a particular type.

Properties can also be used directly in the type itself, this property is called type attribute.

Alternatively, you can define the properties observer to monitor changes in property values, in order to trigger a custom operation. Attribute viewer can be added to write their own memory attribute may be added to the properties inherited from the parent class.


Store Properties

In simple terms, a memory attribute is a constant or variable stored in the instance of a particular class or structure inside.

Storage property can be a variable storage attributes (defined by the keyword var), it can also be a constant storage attributes (defined by the keyword let).

  • You can specify a default value in the property when the definitions are stored

  • You can also set or modify the stored value of the property during construction, and even modify the value of the constant storage property

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 above program execution output is:

67
3.1415

Consider the following code:

let pi = 3.1415

Code pi specify default values ​​stored in the definition attribute when (pi = 3.1415), so no matter when you instantiate the structure, it will not change.

If you define a constant storage property, it will complain if you try to modify as follows:

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

The above program execution error, the error is as follows:

error: cannot assign to property: 'numbers' is a 'let' constant
n.numbers = 8.7

Meaning 'numbers' is a constant, you can not modify it.


Delay Storage Properties

Delay memory attribute refers to the first time when the property is called its initial value will be calculated.

Before using thelazy attribute declaration to indicate a delay store properties.

note:
Delay Storage property must be declared as a variable (using the var keyword), since the value of the property may not be completed before the instance constructor. The constant property before construction is complete must have an initial value, and therefore can not be declared as delayed property.

Delay Storage properties are generally used:

  • Delay the creation of objects.

  • When the value of the property depends on the other unknown class

import Cocoa

class sample {
    lazy var no = number() // `var` 关键字是必须的
}

class number {
    var name = "w3big Swift 教程"
}

var firstsample = sample()
print(firstsample.no.name)

The above program execution output is:

w3big Swift 教程

Examples of variables

If you have had experience in Objective-C, you should know Objective-C class instance storage value and reference provides two methods. For the property, it can also be used as a backend instance variables to store property values.

Swift programming language to use these theories to achieve a unified property. Swift attributes no corresponding instance variables, back-end storage properties can not be accessed directly. This avoids the problems of access methods under different scenarios, but also to simplify the definition of property as a statement.

All the information in a type of property - including name, type, and memory management features - all in a unique place (type definition) definitions.


Calculation Properties

In addition to storage attributes, categories, structures, and enumerations can be defined to calculate property values calculated attribute is not stored directly, but to provide a getter to get the value of an optional setter to set the value of other properties or indirect 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 above program execution output is:

(150.0, 75.0)
-150.0
-65.0

If the calculated property setter does not define the parameter name represents the new value, you can use the default name newValue.


Read-only attribute calculation

Only getter not calculated property setter is a read-only attribute calculation.

Read-only property always returns a calculated value, (.) Operator to access via point, but can not set the new value.

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 above program execution output is:

Swift 属性
3.09

note:

You must use the var keyword to define calculated attributes, including read-only attribute calculation, because their value is not fixed. let keyword is used only to declare a constant attribute that can not be modified after initialization value.


Property Observer

Change attribute viewer to monitor and respond to property value each property is set when the value of the property will be called to observe, and even the new value and the current value of the same time is no exception.

You can add properties to the viewer in addition to the delay memory attribute other than storage properties can also add attributes observer for an inherited property (including storage and computing property attributes) by overriding attribute ways.

note:
You do not need to add a property observer for the calculation of the properties can not be overloaded, because you can directly monitor and respond to changes setter value.

You can add one or all of the following observer for the property:

  • willSet before setting a new value call
  • didSet after a new value is set to call immediately
  • willSet and didSet observer will not be called in the initialization process property
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 is:

计数器: 100
新增数 100
计数器: 800
新增数 700

Global and local variables

Calculation mode attributes and observer described can also be used for global and local variables.

Local variablesGlobal Variables
In the function, method, or internal closures defined variables. Variable outside the function, method, or any type of closure definition.
For storing and retrieving values. For storing and retrieving values.
Storage property to get and set the value. Storage property to get and set the value.
Also used to calculate properties. Also used to calculate properties.

Property Type

Type attribute is defined as part of the type in the type of writing outermost curly braces ({}) inside.

Use the keyword static to define the type attribute value type, class keyword to define a class type attribute.

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:
Computational example of the type attribute is read-only, but you can also define computational readable and writable type attribute syntax similar calculation with the instance attribute.


Get and set the value of the type of property

Examples of similar properties, the type of access to the property is carried out by the dot operator (.). However, the type of property is to get through and set the type itself, rather than by way of example. Examples are 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 above program execution output is:

97
87