zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    LeetCode 914. 卡牌分组
    LeetCode 999. 车的可用捕获量
    LeetCode 892. 三维形体的表面积
    21航电5E
    min25筛 学习笔记
    牛客多校6G
    2021航电多校3
    2021牛客多校H
    [模版] 快速傅里叶变换
    2021牛客多校第五场
  • 原文地址:https://www.cnblogs.com/ficow/p/8227701.html
Copyright © 2011-2022 走看看