As we mentioned previously, accessing a tuple's components via a number is not ideal as we have to remember their order in the tuple to ensure that we are accessing the correct one. To provide some context, we can add labels to the tuple components, which can be used to identify them when they are accessed. Tuple labels are defined in a similar way to parameter labels, preceding the type and separated by a :. Let's add labels to the function we created in this recipe and then use those labels to access the tuple values:
func normalizedStarRating(forRating rating: Float,
ofPossibleTotal total: Float)
-> (starRating: Int, displayString: 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 (starRating: numberOfStars, displayString: ratingString)
}
let ratingAndDisplayString = normalizedStarRating(forRating: 5,
ofPossibleTotal: 10)
let ratingInt = ratingAndDisplayString.starRating
print(ratingInt) // 3 - Use to show the right number of stars
let ratingString = ratingAndDisplayString.displayString
print(ratingString) // "3 Stars" - Use to put in the label
As part of the function declaration, we can see the tuple being declared:
(starRating: Int, displayString: String)
When a tuple of that type is created, the provided values are preceded by the label:
return (starRating: numberOfStars, displayString: ratingString)
To access the components of the tuple, we can use these labels (although the number of indexes still work):
let ratingValue = ratingAndDisplayString.starRating
print(ratingValue) // 3 - Use to show the right number of stars
let ratingString = ratingAndDisplayString.displayString
print(ratingString) // "3 Stars" - Use to put in the label
Tuples are a convenient and lightweight way to bundle values together.