Delegate property with different type in Swift

Ok so we have UIScrollView declaration:

protocol UIScrollViewDelegate: NSObjectProtocol { ... }
class UIScrollView: UIView {
    ...
    weak var delegate: UIScrollViewDelegate?
    ...
}

And then UITableView with delegate variant?

  • How to represent magnitude for mass in Swift?
  • How to properly connect to Google Cast device and cast an url with an custom receiver?
  • Get DNS server IP from iphone settings
  • Custom annotation showing same image for all different types of POI's
  • LLDB throwing auto import error in Swift Xcode project
  • GameplayKit > Scene Editor Navigation Graph > How to use it for pathfinding?
  • 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?’.

    3 Solutions Collect From Internet About “Delegate property with different type in Swift”

    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.

    I got this working but I do not like the solution very much since it throws away type checking.

    What I did was this. In my base class I declared the delegate as

    weak var delegate: AnyObject? = nil
    

    Then, when I want to call a method on the delegate I do

    if let delegate = self.delegate as? MyBaseClassProtocol { delegate.myMethod() }
    

    In my subclass I can then also do the same kind of thing

    if let delegate = self.delegate as MySubclassProtocol { delegate.mySubclassMethod() }
    

    As I say, it works, but I don’t like it much. Throwing away the typechecking is not to be done lightly in my opinion. I am only sharing in the hope someone with stronger Swift skills can improve upon it, or correct it.