1. 程式人生 > >swift protocol(協議) associatedtype關聯類型

swift protocol(協議) associatedtype關聯類型

fun 指定 eth edt 模型 -objc typealias 通過 PE

定義一個協議時,有的時候聲明一個或多個關聯類型作為協議定義的一部分將會非常有用。關聯類型為協議中的某個類型提供了一個占位名(或者說別名),其代表的實際類型在協議被采納時才會被指定。你可以通過 associatedtype 關鍵字來指定關聯類型。比如使用協議聲明更新cell的方法:
  1. //模型
  2. struct Model {
  3. let age: Int
  4. }
  5. //協議,使用關聯類型
  6. protocol TableViewCell {
  7. associatedtype T
  8. func updateCell(_ data: T)
  9. }
  10. //遵守TableViewCell
  11. class MyTableViewCell: UITableViewCell, TableViewCell {
  12. typealias T = Model
  13. func updateCell(_ data: Model) {
  14. // do something ...
  15. }
  16. }

swift protocol(協議) associatedtype關聯類型