Typealiases are used to redefine names for existing types to make code clearer. The syntax is simple, and the TypeAlias keyword can be used to assign a new name to an existing type just like a normal assignment statement. The following code better explains how the TypeAlias * calculates distances and positions on a two-dimensional plane using Double for distances and CGpoints for positions
func distanceBetweenPoint(point: CGPoint, toPoint: CGPoint) -> Double {
let dx = Double(toPoint.x - point.x)
let dy = Double(toPoint.y - point.y)
return sqrt(dx*dx + dy*dy)
}
let origin: CGPoint = CGPoint(x: 0,y: 0)
let point: CGPoint = CGPoint(x:1 , y: 1)
let distance: Double = distanceBetweenPoint(origin, toPoint: point)
print/ / 1.4142135623731 (short)Copy the code
Such code is written and converted when read, which is much easier to understand if typeAlias is used
typealias Location = CGPoint
typealias Distance = Double
func distanceBetweenPoint(point: Location, toPoint: Location) -> Double {
let dx = Double(toPoint.x - point.x)
let dy = Double(toPoint.y - point.y)
return sqrt(dx*dx + dy*dy)
}
let origin: Location = CGPoint(x: 0,y: 0)
let point: Location = CGPoint(x:1 , y: 1)
let distance: Distance = distanceBetweenPoint(origin, toPoint: point)
print/ / 1.4142135623731 (short)Copy the code
Typealias: # Use typeAlias to define a block or closure
Typealias sendValueClosure = (sendString: String) -> Void// declare var callBackString: sendValueClosure? / / hold self callBackString! (sendString: self. NameString) / / callsCopy the code
It’s very convenient to use in # tableView to pass values backwards
Typealias MyFollowerDelegate = MyFollowerViewController extension MyFollowerDelegate: UITableViewDelegate {/ / tableView Typealias MyFollowerDataSouce = MyFollowerViewController Extension MyFollowerDataSouce: UITableViewDataSource} {/ / tableview dataSource methodCopy the code
Separating the proxy method from the data source method makes it more concise.
The same code is much easier to read with the help of TypeAlias. This simple example alone may not make a lot of sense, but when it comes to complex practical problems, you can save a lot of brain cells by not caring about and mapping out what the stacks of ints and strings in your code actually represent. There is no difficulty with common types, but when it comes to generics, things are a little different. First, TypeAliases are single, meaning that you must specify that a particular type be assigned a new name through TypeAlias, not rename the entire generic type. The From meow god