The Problem That Generics Solve

2016-03-06  本文已影响22人  幸运的小强本人

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.

上一篇 下一篇

猜你喜欢

热点阅读