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)

typealias <type name> = <type expression>

Built-in types

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

typealias name = String

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

let kelvin:name = "Kelvin"

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

let kelvin:String = "kelvin"

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

class Gadgets {
  
}

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

var models:[Gadgets] = []

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

typealias Gadget = [Gadgets]

Then create a new variable of Gadget

var gadget: 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.

func method(oncomp:(Int) -> (String)) {

}

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

typealias someName = (Int) -> (String)

And you may rewrite the method as below

func method(oncomp: someName) {
}

 

 

  • 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 *

*
*