Generics (generic) allow us to define a number of mutable parts in a program, specify at runtime, use generics to maximize code reuse, secure types of security, and improve performance.
1. Generic functions
After the function name is added <T>, the parameter type is also declared as t,t as a placeholder, and the function passes in the actual parameter type each time it is called to determine the type of T
Func log4<t> (msg:t) {
println (msg)
}
LOG4 (3)
LOG4 ("Sorry")
Log4 (1.02)
If there are several different types, you can use other uppercase letters, you are generally accustomed to using u, and multiple placeholders are separated by commas:
Examples are as follows:
Func isequals<t,u> (a:t,b:u)->bool {
}
Placeholders can override not only parameter types, but also return value types:
Func isequals<t,u> (a:t,b:u), t{}
2. Generic constraints
Some placeholders must follow a protocol, and the T placeholder is followed by a colon and a protocol type, which is represented as a generic constraint that can replace the type of T.
For example, a comparison function:
Func isequals<t> (A:t, b:t)->bool {
Return (A==B)
}
The above function will compile with an error because not all types are comparable, and the type T represents must conform to the type of the comparable protocol implementation, and the comparable protocol represents comparable:
Modify the following:
Func isequals<t:comparable> (A:t, b:t), Bool {
Return (A==B)
}
This article is from the "Ordinary Road" blog, please be sure to keep this source http://linjohn.blog.51cto.com/1026193/1620386
Swift generics and generic functions