System grooming explaining Swift generics

Source: Internet
Author: User

generics are a very understanding of the grammar, let me very worship!

It's so much love and hate that you're crazy when you don't understand.

Allows a program to define type parameters in functions, enumerations, structs, classes ( types can be changed dynamically )

Each use can pass in different types of parameters!

Array<t> T is generic and represents the type of the array element

struct Dictionary "Key:hashable,value" Key Value is a generic syntax

Array<string> an array of element type bits String

Why do you use it? What kind of convenience does it bring? Take a look at the following example

requirement : The previous array is appended to the last array

Func Copyintarray (src:[int],inout Dest:[int])

{

Traverse and add to the array behind

for element in src{

Dest.append (Element)

}

}

Use

var arr = [2,5]

Copyintarray ([12,9],&arr)

println (arr)//[2,5,12,9]

Then ask you to implement the add string, okay, rewrite a

Func Copystringarray (src:[string],inout dest:[string])

{

for element in src{

Dest.append (Element)

}

}

Use

var strarr = ["OC", "Swift"]

Copystringarray (["PHP", &strarr])

Everybody found out, except for the type, the other code is the same, why do the wheel repeatedly? Merge it. What if there are double types?

Generics are in handy.

Generic function : Specifies one or more type placeholders, type is temporarily indeterminate, and so on when specific calls are determined

Func copyarray<t> (src:[t],inout dest:[t])

{

for element in SRC

{
Dest.append (Element)
}

}

See how powerful it is?

And then feel free to use

var arr = [5,8]

Copyarray ([9,58],&arr)

var strarr = ["Renhairui", "Hello"]

Copyarray (["Nihao", &strarr])

var Doublearr = [1.2,3.4]

Copyarray ([6.5,1.0],&doublearr)

T is a type placeholder and can be used as a normal type

Using generics to make functions more adaptable

Let's go deeper: Define multiple type parameters

Requirements: Projection operation, array type indeterminate, how to project indeterminate, return value type indeterminate

Define two types of parameters first

Srctype represents the element type that needs to execute the projected array

Dsctype the resulting element type

Func projection<srctype,desctype> (SRC:[SRCTYPE],FN: (srctype)->desctype)->[desctype]

{

var result = [Desctype]

for element in SRC

{

Use the FN function to perform a projection operation on an array element, adding the result of the operation to a result array

Result.append (fn (Element))

}

}

Use

var books = ["Ninhaire", "IOS", "engineer"]

Using trailing closures

var proj1 = projection (books) {
Countelements ($)//Calculate element length
}

println (PROJ1)//[3,3,8]

If

var proj2 = projection (books) {
"<" +$0+ ">"

}

println (PROJ2)//["< Ninhaire >", "<iOS>", "<engineer>"]

Again like

Books = ["PHP", "IOS", "Swift"]

var proj3 = projection (books) {
(b:string), (string,string) in

return (b, "Ninhaire")

}

println (PROJ3)//["PHP, Ninhaire", "IOS, Ninhaire", "Swift, Ninhaire"]

Alternatively, you can change the type of books, any type.

Defining generic types

struct rect<t>

{
var x:t

var y:t

var width:t

var height:t

Calculated properties

var position: (t,t)

{
Return (SELF.X,SELF.Y)
}
}

Use

Let rect = rect<double> (x:1.2,y3.4,width:8.5,height:7.8)

Let (x, y) = Rect.position

println ("\ (x), \ (y)")

Let Rect2 = rect<int> (x:3,y:6,width:10,height:30)

Let (x, y) = Rect.postion

Class apple<t>

{
var info:t

Init (info:t)

{

Self.info = info

}
}

Use

var a1= apple<string> (info: "Apple")

println (A1.info)

var a2 = apple<double> (info:5.6)

Deriving subclasses from a generic class

Class a:apple<t>

{ }

Not perfect as follows:

Subclasses of generic classes are required to also have generic declarations

Extending generic types

Type constraints

Association type

Extend later types to determine association types

System grooming explaining Swift generics

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.