Type aliases in Swift — Real tips

Photo by John Schnobrich on Unsplash

Original Post

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.

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.

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

//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.

//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

//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.

//After
typealias VoidCallback = () -> Void
typealias Callback<T> = (T) -> Void
var itemDidChoosed1: VoidCallback?
var authorDidChooseWithIndex1: Callback<Int>?
var userItems1: Callback<[String: Double]>?

iOS Software Developer