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

  • Hands-On Design Patterns with Swift
  • Florent Vilmart Giordano Scalzo Sergio De Simone
  • 167字
  • 2021-07-02 14:45:01

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.

主站蜘蛛池模板: 霞浦县| 宜君县| 临桂县| 建湖县| 阿图什市| 安阳市| 阿巴嘎旗| 久治县| 嵊泗县| 彩票| 大竹县| 余姚市| 永善县| 津市市| 吐鲁番市| 项城市| 广宗县| 南雄市| 安徽省| 巴中市| 姜堰市| 英山县| 永寿县| 界首市| 金门县| 涟源市| 新津县| 孝义市| 依兰县| 台州市| 鸡东县| 泽州县| 铁岭市| 仙居县| 静乐县| 开化县| 深州市| 聂荣县| 靖边县| 柘城县| 苏尼特左旗|