iOS Learning note 43-swift (iii) class

Source: Internet
Author: User

First, Swift's class

As an object-oriented language, classes are also a very important type of swift, so let's look at a simple class

a class in//swift can not inherit from any other base class, so this class is itself a base classClass Person {//define Properties    varName:stringvarHeight =0.0    //constructor method, note that if you do not write a constructor method, the default automatically creates a parameterless constructor methodInit (name:string) {self.name = name}//destructor method, called when the object is disposed, similar to OBJC's dealloc, note that there are no parentheses and arguments, and cannot be called directlydeinit{println("Deinit ...")    }//Define Object methods    funcShowMessage () {println("name=\ (name), height=\ (height)")    }    }//Create Objects of classvarp = person (name:"Liuting") P.height =170.0P.showmessage ()//Result: name=liuting,height=170.0//class is a reference typevarP2 = Pp2.name ="Xiaoming"println(P.name)//Result: Xiaoming//"= = =" means equivalent, cannot use equals "= =", equals to compare values equal, p and P2 are different values, but point to the same objectifp = = = P2 {println("P===P2")//p is equivalent to P2, which means they point to the same object}
Second, the attribute

The concept of member properties is diluted in swift, and attributes are divided into two types:
1. Storage Properties :
Storing properties is more like member variables in other languages, conceptually or declaratively, but the difference is:
* Can control read and write operation ( var indicates readable and writable, let indicates read-only)
* Property changes through the property monitor ( willSet , didSet )
* Fast implementation of lazy loading function ( lazy retouching)
2. Calculate the Properties :
A computed property does not store a value directly, but instead provides a getter value for it, or setter indirectly sets other properties.

The following is an example of an object property usage:
 class  account {    //Define storage properties, set default values, add property listeners    varBalance:double =0.0{//Called when the value is about to be assignedwillset{//Note that changing the value of balance at this time is not used             Self. Balance =2.0            //newvalue represents the new value that is about to be assigned, and calling the property inside the property monitor does not cause the monitor to loop the callprintln"Account.balance willset,newvalue=\ (NewValue), value=\ (self.balance)")        }//When the assignment is complete, calldidset{//Note that changing the value of balance at this time will serve as the final result             Self. Balance =3.0            //oldvalue represents an old value that has already been assigned, and calling the property inside the property monitor does not cause the monitor to loop the callprintln"Account.balance didset,oldvalue=\ (OldValue), value=\ (self.balance)")        }    }} class  person {    //firstname, LastName, age are storage properties    varFirstname:stringThe//var definition indicates that the storage property is readable and writable    varLastname:string Let Age:intThe//let definition indicates that the storage property is read-only    //lazy loading of properties, first access is initializedLazyvarAccount = account ()//lazy-loaded properties in Swift are not necessarily object types, they can also be basic types    //fullname is a computed property that does not directly access the computed property in the get and set methods, otherwise it causes a loop call    varfullname:string{//Gets the computed property when calledget{returnFirstName +"."+ LastName}///Set this calculation property when calledset{the NewValue in the//set method represents the new value that will be assigned, here is the split stringLetArray= Split (NewValue, MaxSplit:Int.max, allowemptyslices:false, IsSeparator: {$0=="."})if Array. Count = =2{FirstName =Array[0] LastName =Array[1]            }        }    }//constructor method, note that if you do not write a constructor method, the default automatically creates a parameterless constructor methodInit (firstname:string, lastname:string, Age:int) { Self. FirstName = FirstName Self. LastName = LastName Self. Age = Age}//Definition methodFunc showmessage () {println ("Name=\ (Self.fullname), age=\ (self.age)")    }}//Create Objectsvarp = person (firstName:"Liu", LastName:"Ting", Age: A) P.showmessage ()//Result: name=liu.ting,age=22P.fullname ="Liu.haha" //Set calculation propertiesP.showmessage ()//Result: name=liu.haha,age=22P.account.balance =Ten/* Below is the Store property listener method Printing: Account.balance willset,newvalue=10,value=0.0account.balance didset,oldvalue=10,value=3.0*/ println"p.account.balance=\ (p.account.balance)")//Result: p.account.balance=3.0
    1. A computed property does not store a value directly, but rather provides getter a value, or setter indirectly sets another property;
    2. lazyThe property must have an initial value and must be a variable that cannot be a constant, because the constant has determined the value before the construction is complete;
    3. The stored property must have a value (except an optional type) before the object method is constructed, whether it is a variable property or a constant property, which can be specified either at the time the property is created or within the constructor method;
    4. The default value setting for a stored property does not cause a call to the property monitor (another assignment in the constructor method does not cause a property monitor call), and only the external setting of the store property causes the property monitor to call;
In addition to the object properties above, we can also define the properties of the class:
class Student {    //定义类的属性只需要在前面加static关键字即可,也是分为存储属性和计算属性,这里是计算属性    staticvar skin:Array<String>{        //只定义了getter,表示该计算属性是只读的        get{            return ["yellow""white""black"]        }    }}//读取类的属性forin Student.skin {    println(color)}
Methods in Swift's class can be divided into the following categories:
    1. Constructor method
      • Default constructor method (overridden when there is a specified constructor method with parameters)
      • Specifying the constructor method
      • Convenient constructor method
    2. destructor method
    3. Object methods
    4. Class method
Here are examples of methods used:
Class Person {//define Properties    varNameString    varHeight:doublevarAge= 0    //1.2. Specify the constructor method, and note that if you do not write a constructor method, a non-parametric construction method is automatically created by defaultInit (Name:String, height:double, Age:int) { Self.Name=Name Self.Height=Height Self.Age=AGE}//1.3. Facilitates the construction method by invoking the specified construction method and providing default values to simplify the construction method implementationConvenience init (Name:String){ Self.Init (name:name, Height:0.0, Age:0)    }//2. Destructors, called when an object is disposed, note that this method has no parentheses, no arguments, and cannot be called directlydeinit{println ("Deinit ...")    }//3. Object MethodsFunc modifyinfowithage (Age:int, height:double) { Self.Age=Age Self.Height=Height}//4. Class methods, which are class-modified methodsClass Func Showclassname () {println ("Class name is a person")    }      }//Create objects by convenient construction methodvarP=Person (name:"Liuting")//Call object methodP.Modifyinfowithage ( A, Height: the)//Call class methodPerson.Showclassname ()
    1. In addition to the constructor method and the destructor method, the parameters of the other methods are default except the first parameter is the local parameter, starting from the second parameter is both a local parameter and an external parameter. However, for a function, by default only the default parameter is both the local parameter and the external parameter, and the other parameters are local parameters.
    2. All parameters of the constructor method are both external and local parameters by default
    3. Only the convenience constructor method can invoke the specified construction method of the current class
    4. The specified constructor method with parameters overrides the call to the default parameterless constructor method
    5. Before an object is freed, it automatically calls its own destructor, and then calls the destructor of the parent class one layer at a level.
Four, subscript script

The subscript script is a shortcut to access the collection, and if our custom class has the function of a collection type, we can define the subscript script to quickly access the Class property and define the subscript scripts to be subscript done by keyword.

classRecord {//define attributes, store is the storage structure inside the record, here is the dictionary    varstore:[String:String]//Specify construction methodInit (data:[String:String]) {Self.store = data}//Subscript script, subscript index for shaping (note also can implement only Getter's read-only subscript script)Subscript (Index:int)String{get{//Dictionary key is sorted and the value of the dictionary is obtained according to the index shaping indexes            varKey = Sorted (Array(Self.store.keys)) [Index]returnself.store[key]! } set{//Dictionary key is sorted after you set the value of the dictionary according to the index shaping indexes            varKey = Sorted (Array(Self.store.keys)) [index] self.store[key] = newvalue//newvalue and properties are used as}    }//Subscript script, subscript index As StringSubscript (Key:String),String{get{returnstore[key]! } set{Store[key] = newvalue}}}//Create ObjectsvarRecord = record (data:["Name":"Liuting","Sex":"Male"]) println ("r[0]=\ (record[0])")//Result: r[0]=liutingrecord["Sex"] ="female"println (record["Sex"])//Result: Female
V. Inheritance

Like OBJC, Swift is also single-inherited (multiple protocols can be implemented, at which point the protocol is placed), subclasses can invoke the parent class's properties, methods, override the parent class's methods, add property monitors, and even rewrite read-only properties to read-write properties.

//Define a parent class class  person {    varFirstname:stringvarLastname:stringvarAge:int =0    varfullname:string{Get{returnFirstName +" "+ LastName}}//Specify construction methodInit (firstname:string,lastname:string) {self.firstname = FirstName self.lastname = lastName}//Object MethodsFunc showmessage () {println ("Name=\ (Self.fullname), age=\ (self.age)")    }//through Final declaration, subclasses cannot override    FinalFunc SayHello () {println ("Hello world.")    }}//define sub-class class Student:  Person {    //Override properties, add a monitor for attributes, override requires the override keyword    Override varfirstname:string{willset{println ("FirstName Willset")} didset{println ("FirstName Didset")        }    }//Add sub-class properties    varScore:double//Subclass Specifies the constructor method that must be called by the parent class constructor method    //And the parent class construction method must be called after the subclass storage property has been initializedInit (firstname:string, lastname:string, score:double) {Self.score = ScoreSuper. Init (Firstname:firstname, Lastname:lastname)}//Convenient construction methodConvenience init () {Self.init (firstName:"", LastName:"", Score:0)    }//Rewrite a read-only property to a writable property    Override varfullname:string{Get{return Super. fullName; }Set{Let array = Split (NewValue, MaxSplit:Int.max, allowemptyslices:false, IsSeparator: {$0=="."})ifArray.count = =2{firstName = array[0] LastName = array[1]            }        }    }//Overriding object methods    OverrideFunc showmessage () {println ("Name=\ (Self.fullname), age=\ (Self.age), score=\ (Self.score)")    }}//Create sub-class objectvarp = Student () P.firstname ="Liu"P.showmessage ()//Result: Name=liu,age=0,score=0P.fullname ="Liu.ting"P.showmessage ()//Result: Name=liu.ting,age=0,score=0P.sayhello ()
    1. You must specify a construction method to invoke the constructor of the parent class.
    2. If a specified construction method with parameters exists in the parent class, the specified construction method of the subclass does not automatically invoke the parent class with the specified construction method without a parameter.
    3. If the parent class has only one parameterless construction method (regardless of whether it contains a convenient construction method), the constructor method of the subclass automatically calls the parent class's parameterless construction method (in which case it is not possible to call manually).
    4. A constant property can only be initialized in the constructor of the class in which it is defined and cannot be initialized in a subclass
    5. Before an object is freed, it automatically calls its own destructor, and then calls the destructor of the parent class one layer at a level.
    6. The convenient construction method must call other specified construction methods in the same class (either specifying a constructor method or facilitating the construction method), and cannot call the parent class constructor method directly.

What questions can be raised in the comments section below! O (∩_∩) o ha!

iOS Learning note 43-swift (iii) class

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.