- Swift 4 Programming Cookbook
- Keith Moon
- 200字
- 2021-07-08 10:21:31
How it works...
A tuple is declared as a comma-separated list of the types it contains, within brackets, for example, (Int, String), as shown in the preceding code. The preceding function, normalisedStarRating, normalizes the rating and creates numberOfStars as the closest number of stars, and ratingString as a display string. These values are then combined into a tuple and returned by placing them, separated by a comma, within brackets as (numberOfStars, ratingString):
let ratingValueAndDisplayString = normalisedStarRating(forRating: 5, ofPossibleTotal: 10)
Calling our function returns a tuple that we store in a constant called ratingValueAndDisplayString. We can access the tuple's components by accessing the zero-based numbered member of the tuple:
let ratingValue = ratingValueAndDisplayString.0
print(ratingValue) // 3 - Use to show the right number of stars
let ratingString = ratingValueAndDisplayString.1
print(ratingString) // "3 Star Movie" - Use to put in the label
There is another way to retrieve the values out of a tuple, and it can be achieved as the value is assigned. By specifying a tuple of variable names, each value of the tuple will be assigned to the respective variable name. Consider the following example:
let (nextValue, nextString) = normalisedStarRating(forRating: 8, ofPossibleTotal: 10)
print(nextValue) // 4
print(nextString) // "4 Star Movie"
- WildFly:New Features
- Rust實戰
- C# 從入門到項目實踐(超值版)
- Java Web及其框架技術
- Bootstrap Essentials
- SQL Server 2016數據庫應用與開發習題解答與上機指導
- 學習OpenCV 4:基于Python的算法實戰
- HTML5 APP開發從入門到精通(微課精編版)
- Visual Studio Code 權威指南
- C++ System Programming Cookbook
- Continuous Delivery and DevOps:A Quickstart Guide Second Edition
- Spring Data JPA從入門到精通
- Flink入門與實戰
- 區塊鏈:技術與場景
- C語言程序設計實驗指導教程