Swift Typealias – Make Your Code Understandable

In Swift, a typealias is an alias for an existing type. It allows you to call one data type by another name.

Using type alias in a strategic way can make your code more readable and understandable.

To declare a new typealias in your project, just use this syntax:

typealias NewType = ExistingType
Typealias in Swift where a number 10 calls itself an int and Number

Next up, I will show you some real-life use cases for typealiases in your Swift program.

By the way, if you want to watch a short video about this topic, look no further:


Typealias Examples

Let’s say you’re dealing with weights in your code. These weights are doubles by data type.

But with a typealias you can create an alias Weight that is actually Double under the hood:

typealias Weight = Double


Now you can use Weight instead of Double:

let mass1: Weight = 152.3
let mass2: Weight = 43.2

print(mass1 + mass2)

Write an Extension for a Typealias

Writing an extension for a typealias also extends the underlying type. For example, assuming that the Weight is in kilos, let’s create an extension toPounds() for the Weight alias:

typealias Weight = Double

extension Weight {
    func toPounds() -> Weight {
        return self * 2.205
    }
}

let mass: Weight = 100
print(mass.toPounds())

// The extension affects Doubles too:
let massDoubles: Double = 120
print(massDoubles.toPounds())



Output:

220.5
264.6


As you can see, both Double and Weight instances now have the toPouds() conversion.

Combine Protocols using Typealias

Assume you have two access protocols for reading and writing students’ grades:

protocol ReadAccess {}
protocol WriteAccess {}


Your teacher should be able to both read and write grades. Using typealias, you can neatly combine these two protocols to create a new protocol dedicated to teacher admins only:

typealias AdminAccess = ReadAccess & WriteAccess
struct Teacher: AdminAccess {}


Closures and Typealias

Let’s say we have a simple method that takes a closure as its input:

func method(operation: (Double) -> (Double)) {}


You can now create a typealias for the (Double) -> (Double) function type to highlight that it is a math operation:

typealias MathOperation = (Double) -> (Double)


Now the method can be updated to use this typealias in its argument’s type:

func method(operation: MathOperation) {}

Conclusion

Typealias is just an alias to an existing type. The main goal of typealiases is to make code more readable and understandable. As an example, here is a typealias Weight that essentially is just a Double:

typealias Weight = Double


Thanks for reading. I hope you find it useful.

Further Reading