美文网首页
Generic Functions

Generic Functions

作者: 幸运的小强本人 | 来源:发表于2016-03-06 23:06 被阅读12次

** Generic functions* can work with any type. Here's a generic version of the swapTwoInts function from above, called swapTwoValues:

func swapTwoValues<T>(inout a: T, inout b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

The body of the swapTwoValues function is identical to the body of the swapTwoInts function. However, the first line of swapTwoValues is slightly different from swapTwoInts. Here's how the first lines compare:

func swapTwoInts(inout a: Int, inout b: Int)
func swapTwoValues<T>(inout a: T, inout b: T)

The generic version of the function uses a placeholder type name (called T, in this case) instead of an actual type name (such as Int, String, or Double). The placeholder type name doesn't say anything about what T must be, but it does say that both a and b must of the same type T, whatever T represents. The actual type to use in place of T will be determined each time the swapTwoValues function is called.

The other difference is that the generic function's name (swapTwoValues) is followed by the placeholder type name (T) inside angle brackets (<T>). The brackets tell Swift that T is a placeholder type name within the swapTwoValues function definition. Because T is a placeholder, Swift does not look for an actual type called T.

The swapTwoValues function can now be called in the same way as swapTwoInts, except that it can be passed two values of any type, as long as both of those values are of the same type as each other. Each time swapTwoValues is called the tye to use for T is inferred from the types of values passed to the function.

In the two examples below, T is inferred to be Int and String respectively:

var someInt = 3
var anotherInt = 107
swapTwoValues(&someInt, &anotherInt)
// someInt is now 107, and anotherInt is now 3

var someString = "hello"
var anotherString = "world"
swapTwoValues(&someString, &anotherString)
// someString is now "world", and anotherString is now "hello"

`The swapTwoValues function defined above is inspired by a generic function called swap, which is part of the Swift standard library. and is automatically made available for you to use in your apps. If you need the behavior of the swapTwoValues function in your own code, you can use Swift's existing swap function rather than providing your own implementation.`

相关文章

网友评论

      本文标题:Generic Functions

      本文链接:https://www.haomeiwen.com/subject/tqmakttx.html