- 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.
推薦閱讀
- Greenplum:從大數據戰略到實現
- App+軟件+游戲+網站界面設計教程
- 工業大數據分析算法實戰
- 云計算與大數據應用
- Sybase數據庫在UNIX、Windows上的實施和管理
- INSTANT Apple iBooks How-to
- 云數據中心網絡與SDN:技術架構與實現
- Solaris操作系統原理實驗教程
- 區塊鏈+:落地場景與應用實戰
- Mastering ROS for Robotics Programming(Second Edition)
- Internet of Things with Python
- Python 3爬蟲、數據清洗與可視化實戰
- 成功之路:ORACLE 11g學習筆記
- Python金融數據挖掘與分析實戰
- Scratch Cookbook