- 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.
推薦閱讀
- Building Computer Vision Projects with OpenCV 4 and C++
- 數(shù)據(jù)庫技術(shù)與應(yīng)用教程(Access)
- Hands-On Machine Learning with Microsoft Excel 2019
- Modern Programming: Object Oriented Programming and Best Practices
- 數(shù)據(jù)結(jié)構(gòu)與算法(C語言版)
- 數(shù)據(jù)庫應(yīng)用基礎(chǔ)教程(Visual FoxPro 9.0)
- 跟老男孩學(xué)Linux運(yùn)維:MySQL入門與提高實(shí)踐
- Learning Proxmox VE
- 大數(shù)據(jù)治理與安全:從理論到開源實(shí)踐
- 智慧城市中的大數(shù)據(jù)分析技術(shù)
- Mastering ROS for Robotics Programming(Second Edition)
- R Machine Learning Essentials
- 信息融合中估計(jì)算法的性能評(píng)估
- AndEngine for Android Game Development Cookbook
- 基于數(shù)據(jù)發(fā)布的隱私保護(hù)模型研究