Ok so we have UIScrollView
declaration:
protocol UIScrollViewDelegate: NSObjectProtocol { ... }
class UIScrollView: UIView {
...
weak var delegate: UIScrollViewDelegate?
...
}
And then UITableView
with delegate
variant?
protocol UITableViewDelegate: NSObjectProtocol, UIScrollViewDelegate { ... }
class UITableView: UIScrollView {
...
weak var delegate: UITableViewDelegate?
...
}
How Apple did this? When I do my
protocol MyScrollViewSubclassDelegate: NSObjectProtocol, UIScrollViewDelegate { ... }
class MyScrollViewSubclass: UIScrollView {
...
weak var delegate: MyScrollViewSubclassDelegate?
...
}
I get Property 'delegate' with type 'MyScrollViewSubclassDelegate?' cannot override a property with type 'UIScrollViewDelegate?'.
The Delegate Pattern in Swift In Swift, a delegate is a controller object with a defined interface that can be used to control or modify the behavior of another object. One example is the UIApplicaitonDelegate in an iOS app.
Protocol is a set of methods (either optional or required) that would be implemented by the class which conforms to that protocol. While, delegate is the reference to that class which conforms to that protocol and will adhere to implement methods defined in protocol.
You don't have to use protocols...but you should if you want to keep things flexible. Delegation is in essence asking someone else to do something for you. If you enforce a contract, then its more likely they will do it for you.
By using the delegate pattern, every developer can easily create a table view and populate it with whatever data they want. Since that data source is a separate object (with the separate concern of coming up with the data) you can attach that same data source to multiple table views. Think of a contact list on iOS.
I stumbled upon this a few times and the only work-around I found was just calling my property something else like customDelegate or whatever you like.
It would be neat indeed to be able to just call it delegate but hey!
MyScrollViewSubclass has the delegate property of UIScrollView because it's subclass of UIScrollView.
As delegate
is already defined by UIScrollView, you cannot define the same property name with a new type.
Change the variable name delegate
to myDelegate
(or something else) and it should work.
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