Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate property with different type in Swift

Tags:

swift

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?'.

like image 897
Stanislav Smida Avatar asked Jul 29 '15 15:07

Stanislav Smida


People also ask

What is delegate property in Swift?

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.

What is difference between protocol and delegate in Swift?

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.

Can delegation be implemented without a 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.

Why use delegate Swift?

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.


2 Answers

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!

like image 70
Skoua Avatar answered Oct 05 '22 06:10

Skoua


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.

like image 31
Ryosuke Hiramatsu Avatar answered Oct 05 '22 06:10

Ryosuke Hiramatsu