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

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.

主站蜘蛛池模板: 砚山县| 达尔| 美姑县| 大城县| 西平县| 郑州市| 神农架林区| 嵊州市| 习水县| 聊城市| 永顺县| 元江| 南岸区| 清远市| 林口县| 武义县| 达日县| 虹口区| 大冶市| 津南区| 永新县| 邢台县| 仲巴县| 昌宁县| 南和县| 辽宁省| 通州市| 宽甸| 营山县| 丹东市| 海淀区| 东安县| 根河市| 诸暨市| 怀化市| 临高县| 麟游县| 石狮市| 台江县| 湘阴县| 八宿县|