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

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.

主站蜘蛛池模板: 措美县| 崇礼县| 长白| 华容县| 泸定县| 嵊州市| 田东县| 芮城县| 雷波县| 万安县| 景泰县| 铅山县| 华阴市| 天峻县| 隆昌县| 阿鲁科尔沁旗| 临夏县| 涡阳县| 璧山县| 鄂伦春自治旗| 余干县| 厦门市| 和平区| 庄浪县| 屏东县| 井冈山市| 张家口市| 余庆县| 五华县| 敖汉旗| 防城港市| 平度市| 临漳县| 龙岩市| 湘潭市| 白河县| 盘锦市| 同德县| 荃湾区| 南丰县| 嵩明县|