首页 > 编程语言 > 详细

Swift typealias associatedType

时间:2018-01-07 12:47:47      阅读:507      评论:0      收藏:0      [点我收藏+]

  

使用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

 

Swift typealias associatedType

原文:https://www.cnblogs.com/ficow/p/8227701.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!