- 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.
推薦閱讀
- 自然語言處理實戰:預訓練模型應用及其產品化
- Learning SAP Analytics Cloud
- Unity Shader入門精要
- HTML5 and CSS3 Transition,Transformation,and Animation
- FFmpeg入門詳解:音視頻原理及應用
- Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
- NetBeans IDE 8 Cookbook
- Advanced Express Web Application Development
- Internet of Things with ESP8266
- SQL Server 2008 R2數據庫技術及應用(第3版)
- 工業機器人離線編程
- 零基礎學HTML+CSS
- Java 9 Programming By Example
- jQuery技術內幕:深入解析jQuery架構設計與實現原理
- Visual Basic程序設計全程指南