A typealias
is used to provide an alternative name for an existing type. It helps improve code readability, especially when working with complex or verbose types. It does not create a new type; it only creates a new name for an existing type.
typealias NewName = ExistingType
typealias Age = Int
func printAge(_ age: Age) {
print("Your age is \(age).")
}
// Example usage
printAge(25) // Output: Your age is 25.
protocol Drivable {
func drive()
}
protocol Fuelable {
func refuel()
}
typealias Vehicle = Drivable & Fuelable
class Car: Vehicle {
func drive() {
print("Driving the car")
}
func refuel() {
print("Refueling the car")
}
}
// Example usage
func operate(vehicle: Vehicle) {
vehicle.drive()
vehicle.refuel()
}
let myCar = Car()
operate(vehicle: myCar)
// Output:
// Driving the car
// Refueling the car