Swift Getting Started tutorial 19-generics

Source: Internet
Author: User

Original blog, reproduced please indicate the source

Blog.csdn.net/hello_hwc

Definition of a generic type

Similar to C + +, generics define a kind of reusable code for any type that implements code in an abstract way. Both the array and the dictionary of Swift are implemented with generics, because arrays can hold variables of type string, or they can be of type int.

As an example,

Func swaptwoints (inout a:int, inout b:int) {let    Temporarya = a    a=b    b = Temporarya}func swaptwostrings (inout A:string, InOut b:string) {let        Temporarya = a        a=b        b = Temporarya}func swaptwodoubles (inout a:double, ino UT b:double) {let        Temporarya = a        a=b        b = Temporarya}
This is the same function structure used to exchange two types, but without generics, we have to define the corresponding function for each type. Very cumbersome.

After using generics, we just need to define

Func swaptwovalues<t> (inout a:t, inout b:t) {Let Temporarya = a    a=b    b = Temporarya}

Here the T is the type, is to tell the compiler, this is a generic type, in the actual operation, there will be a specific type to replace. The type can be either a parameter or a return value. Of course, you can define multiple, such as <T1,T2>

Note: Swift is a type-safe language, and the compiler does type checking if the type mismatch will cause an error.


Two type constraints

In generic definitions, type constraints are important. For example, define a generic to sort a set of data, then this set of data must be able to compare (greater than, equal to, less than), if not, passed in a set of data have both int, and string,int and string to sort, obviously there is no reasonable rule.

A generic constraint indicates that the type must inherit a class, or implement some protocol.

The syntax is as follows

Func Somefunction<t:someclass, u:someprotocol> (Somet:t, someu:u) {//function body goes here}

Then, implement an example that uses type constraints to define generics.

F????? UNC findindex<t:equatable> (array:t[], valuetofind:t), Int? {    for (index, value) in enumerate (array) {            if value = = valuetofind {                return index            }    }    return nil}
Here, the generic defines a function that looks up the specified data in the array, and it is obvious that the type T is to support the = = operator. Equatable is a system-provided protocol that can be used with the = = operator for types that follow this protocol.

Three association types

In the second, we used the system-provided equatable, so how do we customize a similar protocol?

With Association types, the syntax is to use the Typealise keyword in the protocol to define the association type.

Example

Protocol Container {Typealias itemtypemutating func append (item:itemtype) var count:int {get}subscript (i:int)-I Temtype {Get}}
Here, define an association type, ItemType, for the protocol, any struct that follows this protocol must implement a two-way (append,count) subscript script. The specific type of itemtype is determined by the class that follows the agreement. For example

struct Intstack:container {//IntStack

Four where statements

The WHERE statement further constrains the association type. A where statement can allow an association type to follow a specific protocol, or to make the data type of a particular data type consistent with that of the associated type .

Func allitemsmatch<        C1:container, C2:container        where C1. ItemType = = C2. ItemType, C1. Itemtype:equatable> (SOMECONTAINER:C1, ANOTHERCONTAINER:C2), Bool {        if somecontainer.count! = AnotherConta Iner.count {            return False        } for        I in 0..<somecontainer.count {            if somecontainer[i]! = Anothercontainer[i] {                return False            }        }        return True}

There are four constraints defined here

1.C1 must follow the container protocol

2.C2 must follow the container protocol

3.c1 and C2 are itemtype consistent.

4.C1 's itemtype follows equatable protocol.




Swift Getting Started tutorial 19-generics

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.