A tuple is declared as a comma-separated list of the types it contains, within brackets. In the preceding code, you can see a tuple being declared as (Int, String). The function, normalizedStarRating, normalizes the rating and creates numberOfStars as the closest round number of stars and ratingString as a display string. These values are then combined into a tuple by putting them, separated by a comma, within brackets; that is, (numberOfStars, ratingString). This tuple value is then returned by the function.
Next, let's look at what we can do with that returned tuple value:
let ratingAndDisplayString = normalizedStarRating(forRating: 5,
ofPossibleTotal: 10)
Calling our function returns a tuple that we store in a constant called ratingAndDisplayString. We can access the tuple's components by accessing the numbered member of the tuple:
let ratingNumber = ratingAndDisplayString.0
print(ratingNumber) // 3 - Use to show the right number of stars
let ratingString = ratingAndDisplayString.1
print(ratingString) // "3 Star Movie" - Use to put in the label
There is another way to retrieve the components of a tuple that can be easier to remember than the numbered index. By specifying a tuple of variable names, each value of the tuple will be assigned to the respective variable names. Due to this, we can simplify accessing the tuple values and printing the result:
let (nextNumber, nextString) = normalizedStarRating(forRating: 8,
ofPossibleTotal: 10)
print(nextNumber) // 4
print(nextString) // "4 Star Movie"
Since the numerical value is the first value in the returned tuple, this gets assigned to the nextNumber constant, while the second value, the string, gets assigned to nextString. These can then be used like any other constant and removes the need to remember which index refers to which value.