Swift Learning Note 16: protocol

Source: Internet
Author: User
Tags dname

Protocol (protocol)For UnifiedThe name of the method and property, regardless of the function.

Protocolcan be class. Enumeration. Structure implementation. The classes, enumerations, and structs that meet the requirements of the Protocol are called Protocols.The person who follows.
The person who followsneed to provideProtocolSpecifies the members, such as attributes, methods, operators, subscripts, and so on.

I. Basic syntax of the agreement

Let's just start with the code.

Protocol Human {    var name:string{get set}    var isman:bool{set get}    class var Isusable:bool {set Get}  // Class member. Indicates whether the class is available with the    func agedescription (ages:int ...)     function parameters can be variable length parameters}class student{    var name = ""}class primarystudent:student,human{    class var isusable:bool{        get{    return self.isusable    }        set{    self.isusable = newvalue    }    }    var isman:bool    Init (name:string,isman:bool) {        Self.isman = Isman        super.init ()        self.name = name    }    Func agedescription (Ages:int ...) {        var agecount = 0 for age in        ages{            agecount + = age;        }        println ("This man, Age is \ (agecount)")    }}


Key points:
① Compliance with an agreement is required to be like inheritance. In: Add this protocol later
② assumes that both inheritance and compliance are required to put the inherited parent class at the front
③ for the properties in the Protocol, it is necessary to indicate the read/write type of the property, read or write only (cannot be read only)
④ for class members, you need to precede the properties in the protocol with theclasskeyword, let's say class compliance protocol plusclasskeyword, assuming that the enumeration or struct adheres to the protocol plusStatickeyword
the method in the ⑤ protocol supports variable-length parameters, but does not support the default values of the parameters

ii. type of agreement
AlthoughProtocolNo matter what the function itself, butProtocolcan be used as a type.
Usage Scenarios:
protocol Typeas a parameter type or return value type in a function, method, or constructor
protocol Typeas the type of a constant, variable, or property
protocol Typeas an element type in an array, dictionary, or other container

Protocol RandomNumberGenerator {    func random (), Double}class Dice {let    sides:int let    generator:random Numbergenerator    Init (sides:int, generator:randomnumbergenerator) {        self.sides = sides        Self.generator = Generator    }    func Roll (), int {        return int (generator.random () * Double (sides)) + 1    }}class Linearcongruentialgenerator:randomnumbergenerator {    func random ()-Double {        return random ()%10.0    }} var d6 = Dice (Sides:6,generator:linearcongruentialgenerator ())

Explanation:
     in the dice. Generator isRandomNumberGeneratorThe protocol type.

Therefore, It is only possible to assign a value to a class, struct, enumeration type that complies with the RandomNumberGenerator protocol. In the following we can see that the use of compliance with the randomnumbergenerator Protocol at the time of initialization Linearcongruentialgenerator Give him a value.

Iii. entrusted Agent Mode
Played objective-c friends compared to entrusted agent is very familiar with, swift entrusted agent and OC of the same, we still come to see the code bar

Protocol Namecomplete {    func namesetcompleted (thename:string)}class student{    var delegate:namecomplete?    var name:string{    didset{        self.delegate?. namesetcompleted (name)    }    }    init (name:string,delegate:namecomplete) {        self.name = name        Self.delegate = Delegate    }    }class dosth:namecomplete{    func namesetcompleted (thename:string) {        println ("Name:\ (thename) is set")    }}var a = Dosth () var b = Student (name: "", delegate:a) B.name = "Little Wolf"  //output: Name : Little Wolf is set

Explanation:
     Namecomplete is a proxy. Dosth obeys and implements this proxy, student invokes the proxy.

After the name is assigned in student, the Namesetcompleted method in the proxy is called

Iii. Optional Protocol
Friends who have played OC know. Some of the methods that are agreed to in OC are optional. The protocol also has this function in Swift, let's take a look at the following

@objc protocol human{    @optional var name:string{get set}    @optional func descript ()}class student:human{    var name:string = "abc"    Func descript () {    println ("abc")    }}

Key points:
① for an optional method or property. Need to precede a method or attribute with@optionalkeyword
② assumes that an optional method or attribute is included in the protocol and is required to define theProtocol before adding@objckeyword
③ in an optional protocol, there is no type that OC does not have. For example, variable-length type
④ Optional protocol can only be class-compliant

Iv. Agreement Inheritance
protocols are the same as classes. can also inherit

Protocol pname{    var name:string{set get}}protocol dname:pname{    func descript ()}class human:dname{    var Name = ""    func descript () {        println (name)    }}

Explanation:
     dnameinherited thePName, sodnameThe agreement contains not only adescriptmethod also containsnameproperty, so followdnamethe class of the protocol must havenameProperties, anddescriptMethod

v. Synthesis of protocols

Protocol Named {    var name:string {get}}protocol aged {    var age:int {Get}}struct person:named, aged {    VA R name:string    var age:int}func wishhappybirthday (celebrator:protocol<named, aged>) {    println ("Happy Birthday \ (celebrator.name)-you ' re \ (celebrator.age)! ")} Let Birthdayperson = person (name: "Malcolm", age:21) Wishhappybirthday (Birthdayperson)   //Output Happy Birthday Malcolm- You ' re 21!

Explanation:
     Wishhappybirthdaythe parameters passed in by the method are<Named, aged>The synthetic protocol type, at which time an instance of a struct conforming to these 2 protocols can be passed in
Note:
protocol compositing does not generate a new protocol. Instead, multiple protocols synthesize a temporary protocol that goes out of scope and expires.




Swift Learning Note 16: protocol

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.