美文网首页swiftSwift
swift - associatedtype的妙用

swift - associatedtype的妙用

作者: lotawei | 来源:发表于2018-10-19 16:54 被阅读218次
开发中你经常能遇到这样的业务场景.许多列表视图表格数据格式差不多.你会设计很多的协议里面包含各种数据源的类型(取名字毕竟也很麻烦,毕竟还要自己区别了解下),模型创建各种cell如果不想写那么多各种各样的cell(想着复制都是各种cell 去更换名字,设置相应的数据源脑子不好用啊)怎么办?

先看看如果两种cell下
模型一个是 briefdetail 一个是detail 然后在多点有些 skudetail ,类型的数据有差异 cell 不一样布局不一样
但设置数据源的函数自写 都会有个setmodel(data) layoutsubview做布局 这样的操作 类似需要模板设计的思想或者通过继承 多态的方式 可以解决 这里我们采取最简单的方式别名

  • associatedtype
    定义一个协议时,有的时候声明一个或多个关联类型作为协议定义的一部分将会非常有用。关联类型为协议中的某个类型(任意类型)提供了一个占位名(或者说别名),其代表的实际类型在协议被采纳时才会被指定。你可以通过 associatedtype 关键字来指定关联类型,当然你也可以用来设计api用来构建统一的处理结构。比如使用协议声明更新cell的方法:

class  detail {
          //some properties
}
class  briefdetail {
          //some properties
}
class  skudetail {
          //some properties
}

protocol DTCellItemPro {
    associatedtype  T
   func updateCell(_ data: T)
}

class MyDTTableViewCell: UITableViewCell, DTCellItemPro{
    typealias T = detail
    func updateCell(_ data: detail) {
             
    }
}
class MySKUTableViewCell: UITableViewCell, DTCellItemPro{
    typealias T = skudetail
    func updateCell(_ data: skudetail) {
             
    }
}
  


相关文章

网友评论

    本文标题:swift - associatedtype的妙用

    本文链接:https://www.haomeiwen.com/subject/vicqbftx.html