官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 桐城市| 永川市| 广宁县| 中方县| 湄潭县| 高雄市| 胶南市| 崇信县| 翼城县| 文化| 开化县| 新宾| 太原市| 五寨县| 新乐市| 京山县| 醴陵市| 福安市| 永嘉县| 甘南县| 婺源县| 武安市| 西乌| 彭水| 绩溪县| 泰安市| 新河县| 故城县| 庐江县| 西峡县| 辽阳县| 呼图壁县| 成都市| 安多县| 通辽市| 霸州市| 淅川县| 诸暨市| 洪泽县| 石景山区| 清远市|