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) {
...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.