
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