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

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.

主站蜘蛛池模板: 荃湾区| 克拉玛依市| 虹口区| 芮城县| 维西| 库伦旗| 白河县| 南华县| 祥云县| 杨浦区| 黑水县| 闽侯县| 交城县| 博乐市| 河南省| 黑山县| 绥江县| 奉化市| 金阳县| 阿拉善右旗| 青河县| 湖州市| 荆州市| 明水县| 南澳县| 班玛县| 南皮县| 黎城县| 穆棱市| 恩平市| 宜章县| 定安县| 星座| 大兴区| 于都县| 上思县| 大竹县| 温宿县| 石河子市| 于田县| 吉木萨尔县|