Swift Chinese Course (vii) protocols, extensions, and generics

Source: Internet
Author: User

Protocols and Extensions Protocol (interface) and extension

Swift uses the keyword protocol to declare a protocol (interface):

Classes (classes), enumerations (enumerations), and structs (structs) can be implemented using Protocol (protocol):

Class Simpleclass:exampleprotocol {  
    var simpledescription:string = "A very simple class."
    var anotherproperty:int = 69105  
    func adjust () {  
        simpledescription = "Now  100% adjusted."
    }  
}  
var a = Simpleclass ()  
a.adjust () let  
adescription = a.simpledescription  
      
struct simplestructure: Exampleprotocol {  
    var simpledescription:string = "A simple structure"
    mutating func adjust () {  
        Simpledescription + = "(adjusted)"
    }  
}  
var b = simplestructure ()  
b.adjust () let  
bdescription = B.simpledescription

Practice:

Add an enumeration to implement this interface in the example above

Note that the above example uses the MUTATING keyword to declare a method adjust changes the simplestructure structure, while the Simpleclass class does not use the Mutating keyword, because method in the class can change the class at any time. (The implication is that the method in the structure is to mark the change structure with the mutating keyword, which will be explained in subsequent specific translation methods)

Swift uses the extension keyword to extend functionality for an existing type, such as adding a new method or attribute, where you can add a protocol (interface) to a type declared elsewhere, even if it is a referenced library or frame:

Extension Int:exampleprotocol {  
    var simpledescription:string {return  
    "the number \ (self)
    }  
    mutating Func adjust () {  
        self + +  
    }  
}  
7.simpleDescription

Practice:

To add an absolute value attribute to the double type by using the extension keyword

You can use a protocol (interface) like other named types, such as declaring a collection of objects that have different types but adhere to the same protocol (interface). The external method is not available when the value of the Protocol (interface) is run:

1 Let Protocolvalue:exampleprotocol = a
2 protocolvalue.simpledescription
3//Protocolvalue.anotherproperty//The operating environment of this code relies on two examples, and my understanding is that, assuming constant protocolvalue comply with EXAMPLEPROTOCOL protocol, Then the simpledescription in the protocol can be referenced, because it is within the protocol, and Anotherproperty is not the method within the protocol, the operation will be an error, you can try to run, see the wrong results. --by Joe.huang

Although the Protocolvalue and Simpleclass classes are in the same running environment, the compiler places their scope in Exampleprotocol. In other words, we cannot intentionally or unintentionally use a method or attribute outside of the Protocol (interface).

Generics generics

(Refer to generics, must be inseparable from the generic function, ~ ~ ~ ~ ~ ~ ~ ~ ~ ^_^)

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/extra/

Define a generic function or type by using angle brackets <> (pointer naming):

Func repeat<itemtype> (Item:itemtype, Times:int)-> itemtype[] {  
    var result = itemtype[] () to  
    I in 0..t IMEs {result  
        + = Item} return result  
}  
repeat ("knock", 4)

You can use generics in functions (Func), Methods (method), as well as classes (classes), enumerations (enumerations), and Structs (structs):

Overloaded Swift standard library optional type  
enum optionalvalue<t> {case None case  
    Some (T)  
}  
var Possibleinteger:optionalvalue<int> =. None  
Possibleinteger =. Some (100)

Sometimes you need to do something with generics (requirements), such as requiring a generic type to implement an interface or inherit from a particular type, two generic types of the same type, and so on, and Swift where describes these requirements by:

Func anycommonelements <t, U where t:sequence, U:sequence, t.generatortype.element:equatable, T.GeneratorType.Eleme NT = = u.generatortype.element> (lhs:t, rhs:u)-> Bool {for lhsitem in LHS {to Rhsitem in  
        RHS {  
            if L Hsitem = = Rhsitem {return  
                true
            }} is return  
    false
}  
anycommonelements ([1, 2, 3], [3])

Practice:

Modify the Anycommonelements function to return an array with a common element of two sequences

If it's a simple need, you can omit the where keyword, such as <t where t:equatable> can be abbreviated to:<t:equatable>.

To this end, the "Swift programming Language" book in the Language section has been translated, the back of the time began to translate the guide, the project volume is so big Ah, hope to have the time of the students can help in the GitHub on the translation. ^_^

Author: cnblogs Joe.huang

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.