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?
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) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With