- 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.
推薦閱讀
- Python絕技:運用Python成為頂級數(shù)據(jù)工程師
- 云計算環(huán)境下的信息資源集成與服務(wù)
- Effective Amazon Machine Learning
- 從0到1:數(shù)據(jù)分析師養(yǎng)成寶典
- Learning JavaScriptMVC
- 數(shù)據(jù)庫系統(tǒng)原理及應(yīng)用教程(第4版)
- 達(dá)夢數(shù)據(jù)庫運維實戰(zhàn)
- Hadoop大數(shù)據(jù)開發(fā)案例教程與項目實戰(zhàn)(在線實驗+在線自測)
- Python數(shù)據(jù)分析與數(shù)據(jù)化運營
- HikariCP連接池實戰(zhàn)
- SQL Server 2012實施與管理實戰(zhàn)指南
- Doris實時數(shù)倉實戰(zhàn)
- Spring Boot 2.0 Cookbook(Second Edition)
- Hands-On Deep Learning for Games
- 大數(shù)據(jù)隱私保護(hù)技術(shù)與治理機制研究