Typealiases in Swift. Real tips.

Typealiases in Swift. Real tips.

Type aliases easy to use, but it is not clear how and when to use this. It is a default situation when you started to learn protocols for example. Protocols are easy to use and understand, but difficult to implement in a project without experience and real examples.

typealias name = existing type

Default use. You can replace some existing Type on typealias. For example Int on Age. And Age is more convenient to use then Int in this case.

class User {
    
    typealias Age = Int
    
    var age: Age
    
    init(age: Age) {
        self.age = age
    }
    
}

Tuples replace. You can replace some tuples on convenient typealias. And it is easy to use these types in the whole project.

//Before
var car1: (name: String, model: String, topSpeed: Double)
var car2: (name: String, model: String, topSpeed: Double)
var car3: (name: String, model: String, topSpeed: Double)

//After
typealias CarInfo = (name: String, model: String, topSpeed: Double)
var car4: CarInfo
var car5: CarInfo
var car6: CarInfo

Closure replace. It is very useful to replace some huge closure to convenient typealias.

//Before
func example(output: (_ cityName: String, _ temperature: Double) -> Void) {
    //API request
    //....
    //API Response convert to data
    //Here we have 2 variables
    output("New York", 22.0)
}

//After
typealias WeatherOutput = (_ cityName: String, _ temperature: Double) -> Void

func example2(output: WeatherOutput) {
    //API request
    //....
    //API Response convert to data
    //Here we have 2 variables
    output("New York", 22.0)
}

Few required types replace. Protocol-Oriented Programming and various architectures like VIPER make some problems in Type defining (Check my VIPER post here). Problems start when you need that some variable will have two or more types. It is disgusting for code readability and it is cool to have typealias in this case

//Before
var presenter: (PaymentsModulePresenterProtocol & PaymentsModuleProviderResultProtocol & TransactionProcessHandler)?

//After
typealias PresenterProtocol = PaymentsModulePresenterProtocol & PaymentsModuleProviderResultProtocol & TransactionProcessHandler

var presenter2: PaymentsPresenterProtocol?

Combine with Generic use. The closure is widely used in cross modules communication (as like delegate pattern). And you always need to send different data with different types. But it is kind messy without typealias.

//Before
var itemDidChoosed: (() -> Void)?
var authorDidChooseWithIndex: ((Int) -> Void)?
var userItems: (([String: Double]) -> Void)?

//After
typealias VoidCallback = () -> Void
typealias Callback<T> = (T) -> Void

var itemDidChoosed1: VoidCallback?
var authorDidChooseWithIndex1: Callback<Int>?
var userItems1: Callback<[String: Double]>?

Official documentation about typealiases

Photo by John Schnobrich on Unsplash

I hope you enjoyed my short post!