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

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.

主站蜘蛛池模板: 大理市| 青阳县| 仙桃市| 元朗区| 东乡族自治县| 梅河口市| 景德镇市| 交城县| 常州市| 定襄县| 错那县| 荆州市| 闻喜县| 宕昌县| 英德市| 昌吉市| 濉溪县| 淮滨县| 玛多县| 阿鲁科尔沁旗| 长宁县| 青铜峡市| 资中县| 汽车| 濮阳县| 湟源县| 陇南市| 清涧县| 大城县| 岱山县| 鲜城| 福鼎市| 咸宁市| 明溪县| 淮滨县| 闽侯县| 黄骅市| 福清市| 集安市| 安新县| 寿阳县|