Using a typealias to name your tuple type
suggest changeOccasionally you may want to use the same tuple type in multiple places throughout your code. This can quickly get messy, especially if your tuple is complex:
// Define a circle tuple by its center point and radius
let unitCircle: (center: (x: CGFloat, y: CGFloat), radius: CGFloat) = ((0.0, 0.0), 1.0)
func doubleRadius(ofCircle circle: (center: (x: CGFloat, y: CGFloat), radius: CGFloat)) -> (center: (x: CGFloat, y: CGFloat), radius: CGFloat) {
return (circle.center, circle.radius * 2.0)
}
If you use a certain tuple type in more than one place, you can use the typealias
keyword to name your tuple type.
// Define a circle tuple by its center point and radius
typealias Circle = (center: (x: CGFloat, y: CGFloat), radius: CGFloat)
let unitCircle: Circle = ((0.0, 0.0), 1)
func doubleRadius(ofCircle circle: Circle) -> Circle {
// Aliased tuples also have access to value labels in the original tuple type.
return (circle.center, circle.radius * 2.0)
}
If you find yourself doing this too often, however, you should consider using a struct
instead.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents