定义一个 Reusable 协议,遵从这个协议需要有一个静态属性identifier

/// 可复用协议
protocol Reusable: class {
  /// 复用的id
  static var identifier: String { get }
}

利用 swift extention 的特性,让 UIView 默认以类名作为 identifier

extension Reusable where Self: UIView {
  static var identifier: String {
    return NSStringFromClass(self)
  }
}

扩展 UITableViewCell、UICollectionViewCell 都默认实现 Reusable 协议

extension UITableViewCell: Reusable {}
extension UICollectionViewCell: Reusable {}

从此所有 UITableViewCell、UICollectionViewCell 都有了 identifier 属性,不用每次都显示声明 identifier

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.identifier)
    // 做cell处理
    return cell
  }

以此为例,我们如果想要给某些类拥有某些属性并且设置默认值,就可以通过协议扩展的方式实现