上QQ阅读APP看书,第一时间看更新
Using tuples in functions
Tuples are first-class citizens in Swift; you can use them, like any other type, as function parameters. The following code demonstrates how to declare a simple function that computes to the Euclidean distance between two points, a and b, represented by tuples:
func distance(_ a: (Double, Double), _ b: (Double, Double)) -> Double {
return sqrt(pow(b.0 - a.0, 2) + pow(b.1 - a.1, 2))
}
distance(point, origin) == 5.0
You may have noticed that the named parameters of the point tuple are ignored in this case; any pair of Double will be accepted in the method, no matter what they are named.
The opposite is true, as well:
func slope(_ a: (x: Double, y: Double),_ b: (x: Double, y: Double)) -> Double {
return (b.y - a.y) / (b.x - a.x)
}
slope((10, 10), (x: 1, y: 1)) == 1
We've seen examples of using tuples with the same types, but remember that, tuples can contain any type, and as many values as you wish.