如何使用子类遵守协议

onm*_*133 2 protocols class subclass conform swift

说我有一个协议

protocol A: class {
  func configure(view: UIView)
}
Run Code Online (Sandbox Code Playgroud)

现在,我想遵循此协议,将其UILabel用作UIView

final class B: A {
  init() {}

  func configure(view: UILabel) {

  }
}
Run Code Online (Sandbox Code Playgroud)

但是错误

类型B不符合协议A

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

final class B: A {
  init() {}

  func configure(view: UIView) {

  }
}
Run Code Online (Sandbox Code Playgroud)

但是我要使用UILabel,如何解决此问题?

ABa*_*ith 5

您可以使用associatedType类型为的UIView

protocol A: class {
    associatedtype View: UIView
    func configure(view: View)
}
Run Code Online (Sandbox Code Playgroud)

现在在类中B,由于UILabel是的子类UIView,所以可以这样做:

final class B: A {
    init() {}

    func configure(view: UILabel) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)