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

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.

主站蜘蛛池模板: 罗江县| 开江县| 巴林右旗| 高雄县| 宿松县| 宣威市| 沙坪坝区| 康保县| 千阳县| 库尔勒市| 保康县| 石棉县| 百色市| 普格县| 滕州市| 建宁县| 卓尼县| 罗江县| 晋州市| 东丽区| 志丹县| 成武县| 台安县| 墨竹工卡县| 海原县| 从江县| 多伦县| 博罗县| 长兴县| 吴川市| 绥阳县| 昌都县| 桐庐县| 安顺市| 离岛区| 正阳县| 共和县| 忻州市| 临沭县| 喀喇| 中阳县|