typealias
使用typealias为常用数据类型起一个别名,一方面更容易通过别名理解该类型的用途,另一方面还可以减少日常开发的代码量。
- 给已有类型重新定义名称,方便代码阅读
- 定义闭包,类似oc的block 定义
//eg:1.已有类型的重新命名
typealias Address = CGPoint
let point: CGPoint = CGPoint(x: 0,y: 0)
//等价于
let point: Address = CGPoint(x: 0,y: 0)
闭包定义
typealias successCallback = (_ code: String, _ message: String) -> Void
var callBack: successCallback?
self.callBack!(code: "0",message: "ok")
// 网络请求常用回调闭包
typealias success = (_ data: String) -> Void
typealias fail = (_ error: String) -> Void
func fetchData(_ url: String, success: success, fail: fail) {
}
// 用&连接多个协议
typealias UITableViewCommonProtocol = UITableViewDelegate & UITableViewDataSource
class TestDelegate:UITableViewCommonProtocol{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
return cell
}
}
associatedType
associatedtypen表示位置的数据类型,只是先定义一个名字,具体表示的类型要在最终使用的时候进行赋值。在定义协议时,可以用associatedtype声明一个或多个类型作为协议定义的一部分。
protocol NetworkRequest {
associatedtype DataType
func didReceiveData(_ data: DataType)
}
class ViewModel: NetworkRequest {
typealias DataType = String
func didReceiveData(_ data: DataType) {
}
}