0
0
Swiftprogramming~5 mins

Typealias for custom naming in Swift

Choose your learning style9 modes available
Introduction
Typealias lets you give a new, easy name to an existing type. This makes your code simpler and clearer.
When a type name is long or complicated and you want a shorter name.
When you want to give a type a name that fits your app's language or domain better.
When you want to make your code easier to read by using meaningful names.
When you want to switch the underlying type later without changing all your code.
When you want to group related types under a common name.
Syntax
Swift
typealias NewName = ExistingType
Use 'typealias' followed by the new name, then '=' and the existing type.
The new name works exactly like the original type in your code.
Examples
Here, 'Text' is a new name for 'String'. You can use 'Text' anywhere you use 'String'.
Swift
typealias Text = String
This creates 'Age' as a new name for 'Int', making your code clearer when working with ages.
Swift
typealias Age = Int
You can also rename complex types like function types for easier use.
Swift
typealias CompletionHandler = (Bool) -> Void
Sample Program
This program uses 'Score' as a new name for 'Int'. It defines a function that prints the score using the new name.
Swift
typealias Score = Int

func printScore(_ score: Score) {
    print("Your score is \(score)")
}

let myScore: Score = 85
printScore(myScore)
OutputSuccess
Important Notes
Typealias does not create a new type; it only creates a new name for an existing type.
You can use typealias for simple types, complex types, and even function types.
Using typealias can make your code easier to understand and maintain.
Summary
Typealias creates a new name for an existing type to make code clearer.
It works with simple types like Int or String and complex types like functions.
It helps keep your code readable and easier to change later.