Swift:extension and protocol

Source: Internet
Author: User

The expansion function (Extension) inSwiftcan dynamically add functionality to the class, similar to the prototype in Javascript; in objective-c , it is the runtime to make dynamic calls or add functionality.

This is defined in the following way:

Extension SomeType {}

1. Unit conversions

Extension Double {    var km:double {return self * 1000.0}}

The code for the call is as follows:

Let walk:double = 25.4;print ("25.4 km =  \ (walk.km) m")
The resulting output is: "25.4 km = 25400.0 m"

As can be seen from the above definition: we extend a read-only property for type double, so every time we call it, we multiply the result by 1000.0.


2. Digital to Chinese

Func Getchinesenumber (number:int), String {let    chineselist = ' 0123456789 ' let    index = advance (chineselist. StartIndex, number)    return string (Chineselist[index])}extension Int {    func tochiesenumber (), String {        var result:string = ""        var num = self;        while (num > 0) {            result = Getchinesenumber (num%) + result;            num = NUM/10        }        return result;}    }

the code for the call is as follows:

212332423.toChieseNumber ()
The resulting output is: "212332423"

As can be seen from the above definition: we extend a method for type int, which is the function of converting the entered number into a Chinese string.


Second, The protocol in Swift is similar to the interface inC # (Interface), but the protocol in Swift is more powerful, and the protocol can not only define methods,

Attributes can also be defined, and the protocol can be used not only for classes, but also for structs and enumerations.

This is defined in the following way:

Protocol Someprotocol {    //protocol content}class Someclass:somesuperclass, Someprotocol {//    class contents}

As an example:

Protocol fullnamed {    var fullname:string {get}    func greeting () string}class person:fullnamed {    var ful lname:string = ""    init (fullname:string) {        self.fullname = fullName    }    func greeting (), String {
   
    return "Hello" + self.fullname    }}let Zhansan = person (fullName: "Zhang San") println (Zhansan.greeting ())
   

Note: These properties and methods must be implemented in the class in which the related properties or methods defined in Protocol protocol are implemented.

For example, the Fullnamed protocol defines the FullName attribute and the greeting method. There is an implementation in the class person to which it is implemented.

var fullname:string = "" is the implementation of the FullName attribute in the protocol fullnamed.

The Init initialization method further assigns a value to the property fullname.


The benefit of the Protocol is that the protocol only defines attributes or methods without specific implementations, and these implementations are passed to the class or structure that implements the protocol, enumerations, and so on. In this way, it is more advantageous to extract and encapsulate code. And through the agreement can realize the multi-state effect and the factory function and so on.


Third, Swift 's mutating keyword modification method is to be able to modify the struct or enum variable in this method . In a class, it is not necessary, because a method in a class can modify a variable


As an example:
Protocol Vehicle {    var numberofwheels:int {get}    var color:uicolor {Get Set}    mutating func changecolor ()}str UCT mycar:vehicle {let        numberofwheels = 4    var color = uicolor.redcolor ()    mutating func ChangeColor () {
   self.color = Uicolor.graycolor ()    }}

A method ChangeColor is defined in protocol vehicle, and it is decorated with mutating. The benefit is that the ChangeColor method in implementing the structure of the protocol can directly modify the value of its member variable, such as Mycar the value of the color member variable to Graycolor.
Four,A class if two implementations of theProtocol, and these twoProtocolthe method defined may have a resolution with the same nameAs an example:
Protocol A {    func bar ()-Int}protocol b {    func bar ()-String}class dog:a, B {    func bar ()-Int {        return 1    }        func bar (), String {        return "Hello"    }}let instance = Dog () Let num = (instance as A). Bar () Let str = (instance as B). Bar ()

Note that when you call the bar method, you must specify the bar method that is the protocol, so you pass the type conversion.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Swift:extension and 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.