Let's imagine that we are building an app that pulls movie ratings from multiple sources and presents them together to help the user decide which movie to watch. These sources may use different rating systems, such as the following:
- Number of stars out of 5
- Points out of 10
- Percentage score
We want to normalize these ratings so that they can be compared directly and displayed side by side. We want all the ratings to be represented as a number of stars out of 5, so we will write a function that will return the number of whole stars out of 5. We will then use this to display the correct number of stars in our user interface (UI).
Our UI also includes a label that will read x Star Movie, where x is the number of stars. It would be useful 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. Let's get started:
- Create a function to normalize the star ratings. The following function takes a rating and a total possible rating, and then returns a tuple of the normalized rating and a string to display in the UI:
func normalizedStarRating(forRating rating: Float,
ofPossibleTotal total: Float) -> (Int, String) {
}
- Inside the function, calculate the fraction of the total score. Then, multiply that by our normalized total score, 5, and round it to the nearest whole number:
let fraction = rating / total
let ratingOutOf5 = fraction * 5
let roundedRating = round(ratingOutOf5) // Rounds to the nearest
// integer.
- Still within the function, take the rounded fraction and convert it from a Float into an Int. Then, create the display string and return both Int and String as a tuple:
let numberOfStars = Int(roundedRating) // Turns a Float into an Int
let ratingString = "\(numberOfStars) Star Movie"
return (numberOfStars, ratingString)
- Call our new function and store the result in a constant:
let ratingAndDisplayString = normalisedStarRating(forRating: 5,
ofPossibleTotal: 10)
- Retrieve the number of stars rating from the tuple and print the result:
let ratingNumber = ratingAndDisplayString.0
print(ratingNumber) // 3 - Use to show the right number of stars
- Retrieve the display string from the tuple and print the result:
let ratingString = ratingAndDisplayString.1
print(ratingString) // "3 Star Movie" - Use to put in the label
With that, we have created and used a tuple.