Table of contents
In this article, you will learn about typealias and its use cases in Swift, a programming language developed by Apple. A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program.
Type alias do not create new types. They simply provide a new name to an existing type.
The main purpose of typealias
is to make our code more readable, and clearer in context for human understanding.
How to create a typealias?
It is declared using the keyword typealias
as:
1 | typealias name = existing type |
In Swift, you can use typealias
for most types. They can be either:
- Built-in types (for.eg: String, Int)
- User-defined types (for.e.g: class, struct, enum)
- Complex types (for e.g: closures)
Typealias for built-in types
You can use typealias for all built in data Types as String, Int, Float etc.
For example:
1 | typealias StudentName = String |
The above declaration allows StudentName to be used everywhere instead of String
. So, if you want to create a constant of type string but represents more like student name. You can do as:
1 | let name:StudentName = "Jack" |
Without using typealias, you should declare constant of type string as:
1 | let name:String = "Jack" |
Above both examples creates a constant of type String
. But declaring with typealias
, our code becomes more readable.
Typealias for user defined types
There are many cases when you need to create your own data type. Suppose you want to create a Type that represents Student, you can create it using a class as:
1 2 3 | class Student { } |
Now a group of students can be represented as an array as:
1 | var students:Array<Student> = [] |
The above declaration can be made more readable by creating your own type for Array<Student>
using typealias
as:
1 | typealias Students = Array<Student> |
Now we can make our code more readable as:
1 | var students:Students = [] |
Typealias for complex types
Lets analyze one more example. Suppose we have a method that takes a closure as an input parameter.
Don’t worry if you do not know about closures. Just think of it as a special type of function. We have explained it detail in the article: Swift closures.
1 2 3 4 | func someMethod(oncomp:(Int)->(String)){ } |
The above example takes a closure as an input to someMethod
. The closure takes an Int
value and returns String
.
You can see the use of (Int)->(String)
makes less sense to the reader. You can use typealias
to provide a new name for it:
1 | typealias CompletionHandler = (Int)->(String) |
Now you can rewrite the method as:
1 2 3 | func someMethod(oncomp:CompletionHandler){ } |
We can see the same code looks more clear and programmer friendly with the use of typealias
.