The Problem That Generics Solve

Here's a standard, non-generic function called swapTwoInts, which swaps two Int values:

func swapTwoInts(inout a: Int, inout b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

This function makes use of in-out parameters to swap the values of a and `b .

The swapTwoInts function swaps the original value of b into a, and the original value of a into b, You can call this function to swap the values in two Int variables:

var someInt = 3
var anotherInt  = 107
swapTwoInts(&someInt, &anotherInt)
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3"

The swapTwoInts function is useful, but it can only be used with Int values. If you want to swap two String values, or two Double values, you have to write more functions, such as the swapTwoString and swapTwoDoubles functions shown below:

func swapTwoStrings(inout a: String, inout b: String) {
    let temporaryA = a
    a = b
    b = temporaryA
}

func swapTwoDoubles(inout a: Double, inout b: Double) {
    let temporaryA = a
    a = b
    b = temporaryA
}

You may have noticed that the bodies of the swapTwoInts, swapTwoStrings, and swapTwoDoubles functions are identical. The only difference is the type of the values that they accept(Int, String, and Double).

It would be much more useful, and considerably more flexible, to write a single function that could swap two values of any type. Generic code enables you to write such a function.(A generic version of these functions is defined below.)

In all three functions, it is important that the types of a and b are defined to be the same as each other. If a and b were not of the same type, it would not be possible to swap the values. Swift is a type-safe language, and does not allow (for example) a variable of type String and a variable of type Double to swap value with each other. Attempting to do so would be reported as a compile-time error.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容