Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conform to protocol using subclass

Say I have a protocol

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

Now I want to conform to this protocol, using UILabel as a subclass of UIView

final class B: A {
  init() {}

  func configure(view: UILabel) {

  }
}

But errors

Type B does not conform to protocol A

It seems that Swift needs exactly the same type as stated in the protocol. This works

final class B: A {
  init() {}

  func configure(view: UIView) {

  }
}

But I want to use UILabel, How to work around this?

like image 552
onmyway133 Avatar asked Mar 31 '26 20:03

onmyway133


1 Answers

You could use an associatedType that is constrained to be of type UIView.

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

Now in class B, since UILabel is a subclass of UIView, it's fine to do:

final class B: A {
    init() {}

    func configure(view: UILabel) {
        ...
    }
}
like image 99
ABakerSmith Avatar answered Apr 03 '26 09:04

ABakerSmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!