How and when to use typealias in Swift?

Uplift iOS Interview

"Uplift iOS Interview" is a comprehensive guide to help aspiring iOS developers soar to new heights in their careers. This book is an indispensable tool for anyone looking to crack the iOS interview and impress their future employers with their technical prowess. With in-depth coverage of Swift, AutoLayout, SwiftUI, Multithreading, Memory management so on and so forth, this book is a treasure trove of knowledge for anyone looking to uplift their iOS development career.


The typealias is a simple but powerful concept in Swift. Type alias does not create new types. They simply provide a new name to an existing type. It makes long, compound types easy to manage. In Swift, we are passing the function to another function as an argument very often. In this case, We should use type aliasing to make it more readable. However, when it comes to working with compound types you would definitely notice the benefits of type aliasing. In this short article, I will show some common use of type aliasing.

Type alias is declared using typealias name = existing type

KEY TAKEWAY

Use typealias in closures. Avoid using it in custom dictionary or the type that is more understandable without aliasing.

Use of typealias in closure

Think about an API call which will return String or error as a response. Here, you can notice the first section of code has a lot of parentheses. It looks complicated and ugly. Also, for implementing similar functions, it is not that logical to keep copy-paste the parameters. Using typealias make the signIn function easy to understand.

func signIn(success: ((token: String, message: String, status: Int) -> Void)?, failure: ((Error) -> Void)?) {
    ...
}

// Use typealias

typealias SuccessCallBack = ((token: String, message: String, status: Int) -> Void)?
typealias FailureCallBack = ((Error) -> Void)?

func signIn(
    success: SuccessCallBack,
    failure: FailureCallBack
) {
    ...
}

In combine protocols

Combining multiple protocol helps to understand code with less effort. We can create a type alias by combining multiple protocols. Swift uses this technique almost everywhere. For instance, Codable is a type alias from Encodable and Decodable.

typealias Codable = Decodable & Encodable

protocol Playable {
    func play()
}
protocol Runnable {
    func roamNeighbourhood()
    func walk()
}

typealias CatActiving = Playable & Runnable

struct Cat: CatActiving {
    var name: String
    var breed: String
    ...
}

Use of typealias in generics

Generic typealias can be used since Swift 3.0. In this code example, I use generic array type – typealias array called CartItems. We can make another typealias called Foods from CartItems which provides additional features to the CartItems.

typealias CartItems<T> = Array<T>

typealias Foods<T> = CartItems<T> where T: Equatable

func exoticFood(from foods: Foods<CatFood>) {
    //...
}

When to use typealias?

Don’t use type alias just to represent Swift defined types.

Don’t use type alias if it does not add any value in readability and maintainability.

// Bad use of typealias
typealias CatName = String
struct Cat {
    let name: CatName?
}

// Bad use of typealias
typealias ItemCount = Dictionary<String, Int>
struct Beverage {
    let itemCount: ItemCount?
}

// It is hard to understand, item count is
// an Int or Dictionary or Double.

// This one makes sense because we all know that
// point is the combination of x and y co-ordinate

// Good use of typealias
typealias Point = (Int, Int)
struct Triangle {
    let startingPoint: Point?
    ...
}


Rev Up Your iOS Skills: Take a Dynamic Learning Journey
iOS Career Boost

iOS Career Boost is the ultimate learning journey to elevate your iOS development career through a dynamic blend of visual learning, handy cheat sheets, coding practice materials, and expertly curated tips and tricks


Get Ready to Shine: Mastering the iOS Interview


Enjoying the articles? Get the inside scoop by subscribing to my newsletter.

Get access to exclusive iOS development tips, tricks, and insights when you subscribe to my newsletter. You'll also receive links to new articles, app development ideas, and an interview preparation mini book. Your email address will only be used for the purpose of sending the newsletter and will not be shared with third parties or advertisers. Rest assured that we value your privacy and will not spam your inbox.


Connect with me on

Twitter and LinkedIn and don't hesitate to reach out with any questions about this post. Thank you for reading.

If you know someone who would benefit from reading this article, please share it with them.