Type aliases in Swift — Real tips

Image for post
Image for post
Photo by John Schnobrich on Unsplash
typealias name = existing type
class User {

typealias Age = Int

var age: Age

init(age: Age) {
self.age = age
}

}
//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
//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)
}
//Before
var presenter: (PaymentsModulePresenterProtocol & PaymentsModuleProviderResultProtocol & TransactionProcessHandler)?
//After
typealias PresenterProtocol = PaymentsModulePresenterProtocol & PaymentsModuleProviderResultProtocol & TransactionProcessHandler
var presenter2: PaymentsPresenterProtocol?
//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]>?

iOS Software Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store