English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Type Aliases (Typealias)

In this article, you will learn about type aliases in Swift and their use cases.

Type aliases allow you to name the existingData typesProvide a new name. After declaring a type alias, you can use the alias instead of the existing type throughout the program.

Type aliases do not create new types. They just provide a new name for 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 type alias?

Declared using the typealias keyword:

typealias name = existing type

In Swift, most types can be used with typealias. They can be:

  • Built-in types(For example: String, Int)

  • User-defined types(For example: classes, structures, enumerations)

  • Complex types(For example: closures)

Type alias for built-in types

You can use typealias for all built-in data types, such as String, Int, Float, etc.

For example:

typealias StudentName = String

The above declaration allowsStudent nameIn place of String. So, if you want to create a string type constant but it is more like a student's name, you can do it like this:

let name: StudentName = "Jack"

Without using typealias, the string type constant should be declared as:

let name: String = "Jack"

In the above two examples, create a String type constant. However, using typealias for declaration, our code will be more readable.

Type alias for user-defined types

In many cases, you need to create your own data type. Suppose you want to create a type to represent Student, you can use the following class to create it:

class Student {
{}

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

var students: Array<Student> = []

By using typealias to create your own type for Array<Student>, the above declaration can be made more readable:

typealias Students = Array<Student>

Now, we can make the code more readable:

var students: Students = []

Complex type alias

Let's analyze another example. Suppose we have a method that takes a closure as an input parameter.

If you are not familiar with closures, don't worry. Just treat it as a special function.

func someMethod(oncomp: (Int)-> (String)){
{}

The above example takes a closure as the input of someMethod. The closure takes an Int value and returns a String.

You can see (Int)-> The use of (String) has no meaning for developers. You can use typealias to provide it with a new name:

typealias CompletionHandler = (Int)-> (String)

Now, you can rewrite the method as:

func someMethod(oncomp: CompletionHandler){
{}

We can see that using typealias, the same code looks clearer and more friendly to programmers.