Swift Typealias

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:

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:

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:

let name:StudentName = "Jack"

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

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:

class Student {

}

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

var students:Array<Student> = []

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

typealias Students = Array<Student>

Now we can make our code more readable as:

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.

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:

typealias CompletionHandler = (Int)->(String)

Now you can rewrite the method as:

func someMethod(oncomp:CompletionHandler){

}

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

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges