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

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.

主站蜘蛛池模板: 舒城县| 涟水县| 犍为县| 峨山| 格尔木市| 内丘县| 会泽县| 苏尼特左旗| 南平市| 库伦旗| 威远县| 高密市| 平泉县| 松潘县| 富裕县| 隆昌县| 射洪县| 慈溪市| 孟州市| 西安市| 东乌珠穆沁旗| 瓮安县| 米泉市| 方城县| 尉犁县| 繁峙县| 平江县| 弥渡县| 澜沧| 河北省| 新营市| 长子县| 福州市| 乌拉特后旗| 建湖县| 枣强县| 佛山市| 孝义市| 读书| 汉中市| 娄底市|