Extended extension and Protocol protocol in "IOS" Swift

Source: Internet
Author: User

Together with the previous several playground summary code to go to GitHub, notes written a lot, the main convenience of their own later can be turned over to see. The main part of Swift syntax is almost all of it. There are, of course, generics, operator overloading, arcs, closures and the like.


One, extension (extension)

Extended Extension ( similar to the classification in OC , but no name in Swift ), even if there is no permission to get the original code, Adds new functionality to the class .

Note : the extension is available to instances of the class as long as the extension is defined .

Extension sometype{    //new features added to SomeType write here}

1.1 Extended Properties ( only computed properties )

Extensions can add new computed properties, but cannot add storage properties (nor can you add property observations). Extension double{  //Add an instance property to an existing type in the API    var km:double {return self * 1_  000.0}    var m:double {return self}    var cm:double {return self/100.0}}let jjlength = 1.m  //1 with M for point operation, Represents a double value of 1 let jjlength_km = 1.kmprintln (10.km + 1.m)

1.2 Extension Constructors

You can customize your own constructor class myclass{    var a:int    init () {        a = ten    }}extension myclass{    convenience init ( var parm:int) {   //Extension constructor        self.init ()        println ("extension constructor---> Traverse Builder, \ (parm)")    }}var MyClass = MyClass (Parm:9)

1.3 extension Methods

here are like extending the myintfunc method in Int

Extension int{    func myintfunc () {        println ("value is \ (self), haha!")    }} 1.myIntFunc ()

1.3.1 Modifying instance methods

By extending the method , You can modify the instance self itself . But we need to add mutating before the method.

Extension double{    mutating func mymoidfyselfvalue{self        = self * Self//Modify the value of self instance    }}var d = 2.0d.mymoidfy Selfvalue ()

1.4 extending nested types

That is, add a new nested type to the existing nested type . You can also extend the subscript ( secondary script ) , and so on .

Extension Character {    enum kind{   //Nested An enumeration type case Big case        Small    }    var k:kind{        if (String (self). lowercasestring = = "a") {            return kind.big        }else{            return kind.small        }    }}var Ch:character = "a" CH.K   //Returns an enumeration value Kind.big

Ii. Agreement (protocol)

You can define methods and properties , which are implemented by specific classes . More and more like Java

The protocols in Swift can be implemented by classes , enumerations , and structs .

Protocol someprotocol{    //protocol content}class someclass:someprotocol{//Implementation protocol, multiple protocols can be implemented    }

Requirements for properties / methods / mutation methods in the 2.1 protocol

Requirements for the 2.1.1 property

Protocol anotherprotocol1{    //class represents a class member (struct/enum with static)    class Var property:int {Get Set}//get, set represents a readable writable}CLA SS anotherclass1:anotherprotocol1{    class var property:int {  //implement the properties in the agreement        get{            return ten        }        set{                    }}}    

2.1.2 Method Requirements

Default parameters are not supported. There is simply no way to implement it. Protocol anotherprotocol2{    func myFunc () Int   //declaration does not implement}class AnotherClass2: anotherprotocol2{    func myFunc () Int {  //implementation method return #}    }

2.1.3 Mutation Method requirements

A method that can change the instance type within a method or function is called a mutation method . (mutating keyword )

In a class , you can not write mutating, but in structs and enumerations China must write

Protocol togg{    mutating func togg ()}enum onoffswitch:togg{    case OFF,        on mutating func Togg () {//change the value of the instance 
   
    switch self{case        . Off: self = on case        . On: Self            = Off        }    }}var lightSwitch = OnOffSwitch.OfflightSwitch.togg ()   //value changed to ON
   

The 2.2 protocol type .

Protocols can also be used as types . This is the same as a function .

1. can be used as parameter / return value type

2. types that can be used as constants / variables / attributes

3. available as array / dictionary and other element types

Protocol myrect{    func mylucknumber () int}class myrectimp:myrect{    func mylucknumber () Int {        Retu RN Ten    }}class Dice {let    sides:int    var gener:myrect    //as type    init (sides:int, gener:myrect) {  / /as parameter        self.sides = sides        Self.gener = gener    }}var dice = Dice (sides:6, Gener:myrectimp ()) Dice.gener.myLuckNumber ()   //Return 10

See Example code: http://github.com/xn4545945/SwiftLearning


Reference:

The Swift programming Language

Apple Dev Center


Reprint Please specify source: http://blog.csdn.net/xn4545945



Extended extension and Protocol protocol in "IOS" Swift

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.