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

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.

主站蜘蛛池模板: 凌云县| 日喀则市| 黎平县| 白水县| 平凉市| 旅游| 九龙城区| 平谷区| 商都县| 磐石市| 平定县| 北川| 威宁| 绥阳县| 合江县| 巩义市| 淮阳县| 衡水市| 岗巴县| 曲阳县| 昭平县| 北辰区| 赤水市| 阿尔山市| 拜城县| 宁陵县| 定南县| 和政县| 巢湖市| 嘉峪关市| 洛宁县| 金堂县| 双城市| 云阳县| 安阳县| 营山县| 陇川县| 富蕴县| 墨江| 汽车| 阿瓦提县|