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

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.

主站蜘蛛池模板: 临沭县| 民县| 麻栗坡县| 诸暨市| 芜湖市| 海盐县| 读书| 陇川县| 格尔木市| 梅河口市| 新疆| 嘉义县| 琼中| 屯昌县| 乌拉特后旗| 育儿| 分宜县| 疏附县| 分宜县| 南部县| 苗栗县| 青岛市| 郁南县| 广宗县| 信阳市| 罗平县| 财经| 进贤县| 双流县| 日喀则市| 岱山县| 荣成市| 安远县| 呼和浩特市| 石门县| 白水县| 铜川市| 昭平县| 繁峙县| 北京市| 台湾省|