如何使用子类来遵守协议

How to conform to protocol using subclass

假设我有协议

protocol A: class {
  func configure(view: UIView)
}

现在我想遵守这个协议,使用UILabel作为UIView

的子类
final class B: A {
  init() {}

  func configure(view: UILabel) {

  }
}

但是错误

Type B does not conform to protocol A

似乎 Swift 需要与协议中所述完全相同的类型。这有效

final class B: A {
  init() {}

  func configure(view: UIView) {

  }
}

但我想使用 UILabel,如何解决这个问题?

您可以使用限制为 UIView 类型的 associatedType

protocol A: class {
    associatedtype View: UIView
    func configure(view: View)
}

现在 class B,因为 UILabelUIView 的子 class,所以可以这样做:

final class B: A {
    init() {}

    func configure(view: UILabel) {
        ...
    }
}