Swift typealias associatedType

  

使用typealias为常用数据类型起一个别名,

一方面更容易通过别名理解该类型的用途,

另一方面还可以减少日常开发的代码量。

 

 

typealias使用实例:

// 网络请求常用回调闭包
typealias SuccessWithMsg = ((_ msg:String) -> Void)
typealias FailWithError = ((Error) -> Void)

// 用&连接多个协议
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来实现泛型

 

associatedType使用实例

protocol AssociatedTypeTestProtocol{
    associatedtype T
    func appendData(_ data:[T])
    func resetData(_ data:[T])
}
class AssociatedTypeTestView:AssociatedTypeTestProtocol{
    
    func appendData(_ data: [TestModel]) { // 在实现协议时指明具体类型
    }
    func resetData(_ data: [TestModel]) { // 与上面的方法的类型必须一致
    }
}

 

 

 

 


Ficow原创,转载请注明出处:http://www.cnblogs.com/ficow/p/8227701.html

 

posted @ 2018-01-07 12:01  Ficow  阅读(340)  评论(0编辑  收藏  举报