Type aliases let you give a new name to an existing type. This makes your code easier to read and understand.
0
0
Type aliases for readability in Swift
Introduction
When a type name is long or complicated and you want a shorter name.
When you want to give a type a name that matches your app's language or domain.
When you want to make your code clearer for others reading it.
When you want to switch the underlying type later without changing all your code.
When you want to group related types under easy names.
Syntax
Swift
typealias NewName = ExistingTypeThe keyword typealias creates the new name.
The new name can be used anywhere the original type is used.
Examples
This creates a new name
Age for the type Int. You can use Age instead of Int to make your code clearer.Swift
typealias Age = Int
This gives a name
Coordinates to a tuple type with two Double values labeled x and y.Swift
typealias Coordinates = (x: Double, y: Double)
This names a function type that takes a
Bool and returns nothing as CompletionHandler. It makes function parameters easier to read.Swift
typealias CompletionHandler = (Bool) -> Void
Sample Program
This program shows how to use type aliases for better readability. We create aliases for Int, a tuple, and a function type. Then we use them in functions and variables.
Swift
import Foundation typealias Age = Int typealias Coordinates = (x: Double, y: Double) typealias CompletionHandler = (Bool) -> Void func printAge(_ age: Age) { print("Age is \(age)") } func move(to point: Coordinates) { print("Moving to x:\(point.x), y:\(point.y)") } func performTask(completion: CompletionHandler) { print("Task started") completion(true) } let myAge: Age = 30 let location: Coordinates = (x: 10.5, y: 20.0) printAge(myAge) move(to: location) performTask { success in print("Task completed with success: \(success)") }
OutputSuccess
Important Notes
Type aliases do not create new types, just new names for existing ones.
You can use type aliases with complex types like tuples and function types.
Using type aliases helps when you want to change the underlying type later easily.
Summary
Type aliases give new names to existing types to make code easier to read.
They are useful for long, complex, or domain-specific types.
Type aliases do not create new types, just new names.