- Swift 4 Programming Cookbook
- Keith Moon
- 210字
- 2021-07-08 10:21:31
There's more...
Accessing a tuple's components via a number is not ideal as we have to remember the order of the tuple members to ensure that we are accessing the correct one; this is even more confusing when the members are of the same type. To provide some context, we can add labels to the tuple members to identify them when they are accessed. Tuple labels are defined in a similar way to parameter labels, preceding the type and separated by a : . Let's add labels to both the tuple declaration and the tuple construction, and when accessed:
func normalisedStarRating(forRating rating: Float,
ofPossibleTotal total: Float)
-> (starRating: Int, displayString: String) {
let fraction = rating / total
let ratingOutOf5 = fraction * 5
let roundedRating = round(ratingOutOf5) // Rounds to the nearest integer.
let numberOfStars = Int(roundedRating) // Turns a Float into an Int
let ratingString = "\(numberOfStars) Star Movie"
return (starRating: numberOfStars, displayString: ratingString)
}
let ratingValueAndDisplayString = normalisedStarRating(forRating: 5, ofPossibleTotal: 10)
let ratingValue = ratingValueAndDisplayString.starRating
print(ratingValue) // 3 - Use to show the right number of stars
let ratingString = ratingValueAndDisplayString.displayString
print(ratingString) // "3 Stars" - Use to put in the label
Now, at the point of access, we can be sure that we have the right tuple member.
推薦閱讀
- UML和模式應用(原書第3版)
- 國際大學生程序設計競賽中山大學內部選拔真題解(二)
- Machine Learning with R Cookbook(Second Edition)
- Learning Informatica PowerCenter 10.x(Second Edition)
- Python零基礎快樂學習之旅(K12實戰訓練)
- x86匯編語言:從實模式到保護模式(第2版)
- Learning Python Design Patterns(Second Edition)
- C語言程序設計案例式教程
- Linux環境編程:從應用到內核
- Julia Cookbook
- GeoServer Beginner's Guide(Second Edition)
- 深入淺出PostgreSQL
- 響應式Web設計:HTML5和CSS3實戰(第2版)
- Solr權威指南(下卷)
- 軟件再工程:優化現有軟件系統的方法與最佳實踐