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

How to do it...

Let's say that we are building an app that pulls together movie ratings from multiple sources and presents them together to help the user decide which movie to see. These sources may use different rating systems, for instance, the number of stars out of 5, points out of 10, or a rating as a percentage, and so on. We want to normalize the ratings before we can display them side by side; this will allow them to be compared directly. We want all the ratings to be represented as a number of stars out of 5, so we will have our function return the number of whole stars out of 5, which we will use to display the correct number of stars in our UI.

Our UI also includes a label that will read x Star Movie, where x is the number of stars. It would be good if our function returned both the number of stars and a string that we can put in the UI. We can use a tuple to do this.

Enter the following into your playground:

func normalisedStarRating(forRating rating: Float, 
ofPossibleTotal total: Float) -> (Int, 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 (numberOfStars, ratingString)
}

let ratingValueAndDisplayString = normalisedStarRating(forRating: 5, ofPossibleTotal: 10)

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
主站蜘蛛池模板: 龙口市| 绍兴市| 涿州市| 都昌县| 阜阳市| 定结县| 白银市| 常州市| 即墨市| 高陵县| 榆林市| 丹凤县| 宁陕县| 敦煌市| 盐池县| 石嘴山市| 微博| 紫云| 岳阳县| 开平市| 崇阳县| 铜鼓县| 罗源县| 怀远县| 金溪县| 澳门| 阳春市| 平凉市| 津市市| 双流县| 遂川县| 友谊县| 大理市| 通榆县| 石渠县| 土默特左旗| 合阳县| 肥东县| 宕昌县| 林甸县| 安图县|