What is typealias?

What is typealias?

A typealias gives you the ability to create a new name for existing type in which when a typealias is created, the alias name can be used instead of the existing type in the program.

However, take note that typealias does not create new type. They only provide new name for an existing type. The main objective of typealias is to make the code more readable, and clearer in context for human understanding.

How to create typealias?

The syntax to create typealias is as shown below in which you replace the bold statement with your desire word. You may use typealias for most types such as built-in types (string, int), user-defined types (class, struct, enum) or complex types (closures)

Built-in types

What the code below, it means that you are allowed to use name everywhere instead of String.

And in order to use the code above, simple type:

The usual way of writing it without the implementation of typealias would simply be

User-defined types

The are some instance where you will be creating your own data type and supposed that we are doing it with typealias. The implementation would simply be as below with the creation of a class

And we will be creating an array from Gadgets class. This is how it is being implemented usually.

But with the use of typealias, it is done differently such as declaring typealias of Gadget with an array of Gadgets. Now Gadget is an array of Gadgets

Then create a new variable of Gadget

Complex types

As the title itself has already mentioned that this is indeed a complex subject. As complex usually utilizes closure. The code below takes in a closure of an int value and return string value.

With the implementation of typealias, this could be rewrite as below.

And you may rewrite the method as below



  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *