Javatpoint Logo
Javatpoint Logo

Swift TypeAlias

Swift Typealias is used to provide a new name for an existing data type in the program. Once you create a typealias, you can use the aliased name instead of the exsisting name throughout the program.

Typealias doesn't create a new data type, it simply provides a new name to the existing data type.

Purpose of using Typealias

The main purpose of using typealias is make our code clearer and human readable.

Create a typealias

Typealias is declared using the keyword typealias:

Swift facilitates you to use typealias for most of the types:

  • 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

Typealias can be used for all built-in data types i.e. String, Int, Float etc.

For example:

Here, we have declared EmployeeName as typealias of String. So, we can use it later instead of String type.

For example:

Without using Typealias, the declaration would be:

By creating Typealias EmployeeName, we can write the same above declaration as:

You can see that both examples create the same constant type string but the later one is more understandable for human.

Typealias for user defined types

In Swift, you can create your own data type. Suppose you have to create a data type Employee, so you can create it using a class as:

Now, you can create a group of employees in an array as:

Here, you can create your own type for array using Typealias to make the code more readable:

Now, the declaration would look like:

It is easy to understand in your code.


Next TopicSwift Enum





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA