The generics parsing _c language in Swift programming

Source: Internet
Author: User

Generic code allows you to write out the functions and types that are flexible and reusable based on your own requirements and apply to any type. It allows you to avoid duplicate code, in a clear and abstract way to express the intent of the code.

Generics are one of the powerful features of Swift, and many of the Swift standard libraries are built out of generic code. In fact, generics are used throughout the entire language handbook, but you don't see it. For example, Swift's array and dictionary types are generic sets. You can create an array of int, and you can create an array of strings, or even any other Swift type data array. Similarly, you can create a dictionary that stores any of the specified types (dictionary), and these types can be unrestricted.

problems solved by generics
here is a standard, non-generic function swaptwoints that is used to exchange two int values:

Copy Code code as follows:

Func swaptwoints (inout a:int, InOut b:int)
Let Temporarya = a
A = b
b = Temporarya
}

This function uses the write read out (in-out) parameter to exchange the values of A and B, refer to the write readout parameter.

The Swaptwoints function can exchange the original value of B to a, or you can exchange A's original value to B, and you can call this function to exchange two int variable values:
Copy Code code as follows:

var someint = 3
var anotherint = 107
Swaptwoints (&someint, &anotherint)
println ("Someint is Now" (Someint), and Anotherint are now \ (Anotherint))
Output ' Someint is ' now, and Anotherint are now 3
The Swaptwoints function is useful, but it can only exchange int values, and if you want to swap two strings or double, you have to write more functions, such as swaptwostrings and Swaptwodoublesfunctions, As shown below:
Func swaptwostrings (inout a:string, inout b:string) {
Let Temporarya = a
A = b
b = Temporarya
}

Func swaptwodoubles (inout a:double, inout b:double) {
Let Temporarya = a
A = b
b = Temporarya
}

You may notice that the swaptwoints, swaptwostrings, and swaptwodoubles functions are the same, except that the variable types passed in are int, string, and double.

But practical applications usually require a more powerful and, as far as possible, more flexibility. A single function that can be used to exchange two of any type values, and fortunately, generic code helps you solve the problem. (one of these generic functions is already defined later.) )

Note: In all three functions, the types of a and B are the same. If A and B are not the same type, they cannot interchange the value. Swift is a type-safe language, so it does not allow a variable of type string and a double type to exchange values with one another. If you do, Swift will report a compilation error.

Generic functions: Type parameters
a generic function can access any data type, such as ' Int ' or ' String '.

Copy Code code as follows:

Func exchange<t> (inout a:t, inout b:t) {
Let temp = a
A = b
b = Temp
}

var NUMB1 = 100
var NUMB2 = 200

println ("Before swapping Int values are: \ (NUMB1) and \ (NUMB2)")
Exchange (&NUMB1, &NUMB2)
println ("After swapping Int values are: \ (NUMB1) and \ (NUMB2)")

var str1 = "Generics"
var str2 = "Functions"

println ("Before swapping String values are: \ (str1) and \ (STR2)")
Exchange (&STR1, &STR2)
println ("After swapping String values are: \ (str1) and \ (STR2)")


When we use playground to run the above program, we get the following results

Before swapping int values are:100
swapping int values are:200 and
before swapping String Valu Es are:generics and functions after
swapping String values are:functions and generics

function Exchange () is used to exchange its description in the above scenario and <T> is used as the type parameter value. This is the first time that a function exchange () is called to return an int value, and the second call function Exchange () returns a string value. Multi-parameter types can include commas separated in angle brackets.

Type parameters are named user-defined to understand the purpose of owning type parameters. Swift provides <T> as the name of the generic type parameter. But image arrays and dictionary parameters can also be named as keys, values to determine that they are entered as "dictionaries."

Generic type

Copy Code code as follows:

struct Tos<t> {
var items = [T] ()
mutating func push (item:t) {
Items.append (item)
}

Mutating func pop ()-> T {
Return Items.removelast ()
}
}

var tos = tos<string> ()
Tos.push ("Swift")
println (Tos.items)

Tos.push ("generics")
println (Tos.items)

Tos.push ("Type Parameters")
println (Tos.items)

Tos.push ("Naming Type Parameters")
println (Tos.items)


Let Deletetos = Tos.pop ()


When we use playground to run the above program, we get the following results

[Swift]
[Swift, generics]
[Swift, generics, Type Parameters]
[Swift, generics, type Parameters, naming type Parameters]

Extending generic types
the extended Stack property should know that the top part of the item is contained in the "extension" keyword.

Copy Code code as follows:

struct Tos<t> {
var items = [T] ()
mutating func push (item:t) {
Items.append (item)
}

Mutating func pop ()-> T {
Return Items.removelast ()
}
}

var tos = tos<string> ()
Tos.push ("Swift")
println (Tos.items)

Tos.push ("generics")
println (Tos.items)

Tos.push ("Type Parameters")
println (Tos.items)

Tos.push ("Naming Type Parameters")
println (Tos.items)

Extension TOS {
var first:t? {
Return items.isempty? NIL:ITEMS[ITEMS.COUNT-1]
}
}

If let-i = Tos.first {
println ("The Top item", "The stack is \ (a)")
}


When we use playground to run the above program, we get the following results

[Swift]
[Swift, generics]
[Swift, generics, Type Parameters]
[Swift, generics, type Parameters, naming type Parameters]

The item named type parameter at the top of the stack.

Type constraint
The Swift language allows type constraints to specify whether type parameters inherit from a particular class, or to ensure protocol conformance criteria.

Copy Code code as follows:

Func exchange<t> (inout a:t, inout b:t) {
Let temp = a
A = b
b = Temp
}

var NUMB1 = 100
var NUMB2 = 200

println ("Before swapping Int values are: \ (NUMB1) and \ (NUMB2)")
Exchange (&NUMB1, &NUMB2)
println ("After swapping Int values are: \ (NUMB1) and \ (NUMB2)")


var str1 = "Generics"
var str2 = "Functions"

println ("Before swapping String values are: \ (str1) and \ (STR2)")
Exchange (&STR1, &STR2)
println ("After swapping String values are: \ (str1) and \ (STR2)")


When we use playground to run the above program, we get the following results

Before swapping int values are:100
swapping int values are:200 and
before swapping String Valu Es are:generics and functions after
swapping String values are:functions and generics

Association type
Swift allows related types and can define internal declarations by the keyword "Typealias" protocol.

Copy Code code as follows:

Protocol Container {
Typealias ItemType
Mutating func append (item:itemtype)
var count:int {Get}
Subscript (i:int)-> ItemType {get}
}

struct Tos<t>: Container {
Original stack<t> Implementation
var items = [T] ()
mutating func push (item:t) {
Items.append (item)
}

Mutating func pop ()-> T {
Return Items.removelast ()
}

Conformance to the Container protocol
Mutating func Append (item:t) {
Self.push (item)
}

var Count:int {
Return Items.Count
}

Subscript (i:int)-> T {
return Items[i]
}
}

var tos = tos<string> ()
Tos.push ("Swift")
println (Tos.items)

Tos.push ("generics")
println (Tos.items)

Tos.push ("Type Parameters")
println (Tos.items)

Tos.push ("Naming Type Parameters")
println (Tos.items)


When we use playground to run the above program, we get the following results

[Swift]
[Swift, generics]
[Swift, generics, Type Parameters]
[Swift, generics, type Parameters, naming type Parameters]

Where clause
type constraints enable users to define parameter requirements for types associated with a generic function or type. The ' WHERE ' clause that defines the related type is declared as part of the type parameter list. The "where" keyword type parameter is followed by the type and the related type of restriction between the related types, and the equality relationship is placed after the list.

Copy Code code as follows:

Protocol Container {
Typealias ItemType
Mutating func append (item:itemtype)
var count:int {Get}
Subscript (i:int)-> ItemType {get}
}

struct Stack<t>: Container {
Original stack<t> Implementation
var items = [T] ()
mutating func push (item:t) {
Items.append (item)
}

Mutating func pop ()-> T {
Return Items.removelast ()
}

Conformance to the Container protocol
Mutating func Append (item:t) {
Self.push (item)
}

var Count:int {
Return Items.Count
}

Subscript (i:int)-> T {
return Items[i]
}
}

Func allitemsmatch<
C1:container, C2:container
where C1. ItemType = = C2. ItemType, C1. Itemtype:equatable>
(SOMECONTAINER:C1, ANOTHERCONTAINER:C2)-> Bool {
Check that both containers contain the same number of items
If Somecontainer.count!= anothercontainer.count {
return False
}

Check each pair of the items to if they are equivalent
For I in 0..<somecontainer.count {
If Somecontainer[i]!= Anothercontainer[i] {
return False
}
}
All items match, so return true
return True
}

var tos = stack<string> ()
Tos.push ("Swift")
println (Tos.items)

Tos.push ("generics")
println (Tos.items)

Tos.push ("Where Clause")
println (Tos.items)

var eos = ["Swift", "Generics", "Where Clause"]
println (EOS)


When we use playground to run the above program, we get the following results

[Swift]
[Swift, generics]
[Swift, generics, where Clause]
[Swift, generics, where Clause]

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.