Learn swift--Properties

Source: Internet
Author: User

Properties
    • Property associates a value with a specific class, struct, or enumeration. A store property stores a constant or variable as part of an instance, while a computed property evaluates (not stores) a value. Computed properties can be used for classes, structs, and enumerations, and stored properties are used only for classes and struct bodies.
    • Storage properties and computed properties are typically associated with instances of a particular type. However, attributes can also be applied directly to the type itself, which is called a type property.
    • In addition, you can define a property watcher to monitor changes in property values to trigger a custom action. Property observers can be added to their own defined storage properties, or to properties inherited from the parent class.

Store Properties

A stored property is a constant or variable stored in a class and struct, and can be used to set an initial value for a stored property when defining a stored property, or to set a value or change a value during the construction process.

Declares a struct struct Customrange {    //The following code defines two attributes, one for the variable and one for the constant and none set the initial value    var firstvalue:int let    length:int}// You can call each constructor method given initial value var range = Customrange (Firstvalue:5, length:6)//Because Firstvalue is a variable can modify the value after initialization Range.firstvalue = 6

Note: Because the struct is a value type, if you instantiate a constant struct, you cannot modify the variable properties in the struct, otherwise you will get an error :

Let Otherrange = Customrange (Firstvalue:3, length:5) Otherrange.firstvalue = 5   //This line code will error because Otherrange is declared constant, Even if the Firstvalue property is a variable, it cannot be modified

Deferred Storage Properties

A deferred store property is a property whose initial value is evaluated when it is first called. When the value of a property depends on an external factor that knows the value after the end of the instance's construction, or when the initial value of the property requires complex or large computations, it can be computed only when needed. declare deferred store attributes with <lazy> keyword, and must be set to variable (VAR)

For example, having a file downloader initializing this downloader consumes a lot of time and resources class Datadownloader {    var filename:string?        Func start () {        fileName = "Swift.data"    }}//For example, there is a file Manager class DataManager {    ///Because the initialization of the downloader is assumed to consume a lot of time and resources So using lazy    lazy var downloader = Datadownloader ()    var search = [String] ()}//Initialize the file Manager at this point Downloader has not been called So downloader will not have the value var manager = DataManager () manager.search.append ("some data")//At this time to the following line of code Downloader will be initialized Manager.downloader.start ()

Calculated Properties

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

struct Point {    var x = 0.0, y = 0.0}struct Size {    var width = 0.0, height = 0.0}struct Rect {    var origin = Poi NT ()    var size = size ()        ///Define Center Property The center property does not do any storage except to modify the value of origin in the get and set methods after the    var center:point {        g Et {let            CenterX = origin.x + SIZE.WIDTH/2 let            centery = origin.y + SIZE.HEIGHT/2            return point (x:center X, Y:centery)        }        set {            origin.x = newvalue.x-size.width/2            origin.y = newvalue.y-size.height/2< c16/>}        //The following set method is equivalent to a name for the new value//        set (Newcenter) {//            origin.x = newcenter.x-size.width/2//            ORIGIN.Y = newcenter.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. A read-only computed property always returns a value that can be accessed through the point operator, but cannot set a new value.

Class Rectangle {    var length = 1.0, Width = 2.0, height = 5.0//    var volume:double {//        get {//            return Leng th * Width * height//        }//    }    //Generally only getter method can be written like the following code, of course, the above can also be    var volume:double {        return length * Width * height    }}let rectangle:rectangle = Rectangle () print ("volume is \ (rectangle.volume)")//Print Out: volume is 10.0

Property Watcher

Property observers monitor and respond to changes in property values, and each time a property is set to a value, the property observer is called, even if the new value is the same as the current value. You can add property observers for storage properties other than deferred storage properties, or you can add property observers for inherited properties, including storage properties and computed properties, by overloading the properties. It is generally not necessary to add a property observer for a computed property that is not overloaded, because it can directly monitor and respond to changes in values through its setter.

Class Person {    var name:string = ' ASK ' {        willset {            print ("The new name is \ (newvalue)")        }        didset{
   
    if name = = "" {                name = OldValue            }            print ("Did set the old name was \ (oldValue) and the current name is \ (name )        }}}let person    = person () Person.name = "Alex"//print: The new name is alex//do set the old name is ASK and T He current name is Alex
   

Note: If you assign a value to a property in the Didset method, then this value will replace the value before the Observer

If you assign the Name property to "" (empty string) ↓

Person.name = ""//Print: The new name is//do set the old name was ask and the current name is ask

Type Property

In C or objective-c, static constants and static variables associated with a type are defined as global static variables. However, in the Swift programming language, the type attribute is written as part of the type definition in curly braces at the outermost of the type, so its scope is within the range supported by the type.

Use keywords static to define type properties. When you define a computed type property for a class (class), you can use keywords class to support subclasses to override the implementation of the parent class. The following example shows the syntax for a stored-type and computed-type property:

Class SomeClass {    static var name = "Class name" {        willset {            print ("Static property would set name value")        }    }    //write class to represent subclasses can override enum struct can not write    class var overrideproperty:int {        return SomeClass.name.characters.count    }}print ("name is \ (someclass.name) length is \ (someclass.overrideproperty)")  Someclass.name = "The Some class" print ("name is \ (someclass.name) length is \ (someclass.overrideproperty)")//print 1 name is Class name length is 10//     2 static property would set name value//     3 name is the some class length is 14

Learn swift--Properties

Related Article

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.