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

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.

主站蜘蛛池模板: 陇川县| 芦山县| 平罗县| 澄城县| 商丘市| 府谷县| 赤壁市| 曲松县| 泽州县| 神农架林区| 离岛区| 红桥区| 东山县| 新宁县| 东源县| 三原县| 合作市| 潞西市| 合作市| 阳山县| 浦城县| 稷山县| 镇原县| 甘孜县| 电白县| 彩票| 陇南市| 德化县| 个旧市| 明水县| 临夏市| 奉贤区| 汕尾市| 高尔夫| 修武县| 顺平县| 台前县| 道孚县| 恭城| 永丰县| 秦皇岛市|