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

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
主站蜘蛛池模板: 冕宁县| 祁阳县| 道孚县| 左云县| 阜城县| 明水县| 乌拉特中旗| 徐闻县| 普宁市| 郴州市| 郯城县| 江都市| 涿鹿县| 元阳县| 封丘县| 当涂县| 拉萨市| 华坪县| 诏安县| 肇源县| 芦山县| 阿拉善左旗| 樟树市| 大姚县| 平罗县| 建德市| 攀枝花市| 大同市| 淮北市| 济阳县| 息烽县| 康马县| 裕民县| 辽阳县| 朝阳县| 柳江县| 平武县| 崇阳县| 驻马店市| 万山特区| 桃江县|