1. Overview
Generics are one of the most powerful features of Swift, using generics to write flexible, reusable, clean, abstract code, and avoid code duplication. In fact, in the first chapter we are exposed to generics, arrays and Dictionary are generic containers and can be stored in any type.
2. The problem to be solved by generics the problem that generics Solve
The following defines a function to exchange two values, which does not use a generic attribute:
func swaptwoints (inoutinout b:int) { = a = b = Temporarya }
var 3 var 107 swaptwoints (&someint, &anotherint) println ("someint is now \ ( Someint), and Anotherint are now \ (anotherint)") // prints" Someint are Now 107, and Anotherint are now 3 "
function swaptwoints can only be used for shaping, and then define two functions:
func swaptwostrings (inout a:string, inout b:string) { = a = b = Temporarya } func swaptwodoubles (inout a:double, inout b:double) { = a = b = Temporarya }
3. Generic method Generic Functions
A generic method can be used for any type, and the above method is defined using a generic method:
func swaptwovalues<t>(inoutinout b:t) { = a = b = Temporarya }
Compare them to different points:
The generic version uses a placeholder (the function above is T), which represents the actual type (Int, String, Double). The placeholder t does not indicate the specific type of T, merely indicates that both A and B must be of the same type T. The true type of T is determined only when Swaptwovalues is called.
Angle brackets <> is used to indicate that T is a placeholder that represents a type.
Call the generic function defined above:
varSomeint =3 varAnotherint =107Swaptwovalues (&someint, &anotherint)//Someint is now 107, and Anotherint are now 3 varsomestring ="Hello" varAnotherstring =" World"Swaptwovalues (&somestring, &anotherstring)//somestring is now "world", and anotherstring are now "Hello"
Note: The generic function swap is defined in the SWIFT standard library, which is the same as the function above.
4. Type Parameters
In swapTwoValues The example above, T is the Type Parameter.
Once you have specified a type parameter,
Not to be continued
21. Generic type Generics