Typealias is a mechanism for creating aliases for existing types, which enhances code readability, improves project maintenance, and allows for the reuse of abstractions.
Background
Typealias emerged as a legacy from many other languages, such as typedef in C. In Swift, typealias is built into the type system and is actively used for generic types and protocols with associated types.
Problem
In large projects, long generic types, composite types, compositions, and nested types are often encountered. Without aliases, such constructs become unreadable and complicate application maintenance.
Solution
Declaring typealias for frequently used or complex types simplifies the code, makes it clearer, and more structured. Typealias is also often used to assign aliases to protocols with associated types, circumventing the limitations of protocols as types.
Example code:
typealias JSON = [String: Any] typealias CompletionHandler = (Result<Int, Error>) -> Void typealias StringDictionary = Dictionary<String, String> typealias Handler = (String) -> Void
Key features:
Can you create a new type with typealias?
No, typealias does not create a new type — it is merely an alias, a complete synonym for an existing type, and the compiler treats them as the same type.
typealias Age = Int let a: Age = 25 let b: Int = a // All correct
Will typealias work at the type safety level?
No, typealias does not protect against passing the wrong type: JSON and [String: Any] are interchangeable. To control or separate logic, you need to use separate structures/wrapper objects, not typealias.
typealias UserID = Int typealias ProductID = Int func logId(_ id: UserID) {} let productId: ProductID = 42 logId(productId) // The compiler does not generate an error!
Can you declare typealias inside protocols or generic types?
Yes, associated types or typealias are often declared inside protocols, especially for complex generic types or custom interfaces.
protocol DataSource { associatedtype Item typealias CompletionBlock = (Item) -> Void }
All model identifiers declared via typealias as Int:
typealias UserID = Int typealias ProductID = Int func deleteUser(id: UserID) func deleteProduct(id: ProductID)
Pros:
For a complex generic type or closure return type, declare typealias:
typealias Completion<T> = (Result<T, Error>) -> Void let completion: Completion<String>
Pros: