上QQ阅读APP看书,第一时间看更新
Generics
Generic code enables us to write flexible and reusable functions and types that can work with any type, subject to requirements that we define. For instance, the following function that uses in-out parameters to swap two values can only be used with Int values:
func swapTwoIntegers(a: inout Int, b: inout Int) {
let tempA = a
a = b
b = tempA
}
To make this function work with any type, generics can be used, as shown in the following example:
func swapTwoValues<T>(a: inout T, b: inout T) {
let tempA = a
a = b
b = tempA
}
Generics will be covered in detail in Chapter 5, Generics and Associated Type Protocols.