A.I, Data and Software Engineering

TYPEALIAS in swift ios


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.

swift programming language

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:

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:

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:

Without using typealias, you should declare constant of type string as:

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:

Now a group of students can be represented as an array as:

The above declaration can be made more readable by creating your own type for Array<Student> using typealias as:

Now we can make our code more readable as:

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.

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:

Now you can rewrite the method as:

We can see the same code looks more clear and programmer friendly with the use of typealias.

Add comment

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.

Pin It on Pinterest


You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Petaminds will use the information you provide on this form to be in touch with you and to provide updates.