官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 东辽县| 尤溪县| 泰安市| 溧阳市| 康平县| 张家港市| 进贤县| 新河县| 万宁市| 霞浦县| 阿巴嘎旗| 宝鸡市| 高邑县| 通榆县| 涪陵区| 塔河县| 喜德县| 贵南县| 永定县| 南木林县| 吴江市| 蕲春县| 独山县| 根河市| 尉氏县| 益阳市| 武清区| 利川市| 怀宁县| 靖西县| 隆林| 黄山市| 南康市| 宁德市| 洪洞县| 海原县| 通辽市| 上虞市| 平顶山市| 佛山市| 潍坊市|