Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding superclass property with different type

Tags:

syntax

ios

swift

The following code throws an error

protocol WhatA: AnyObject {
    func doThat()
}

protocol WhatB: WhatA {
    func doThis()
}

class SomethingA {
    weak var delegate: WhatA?
}

class SomethingB: SomethingA {
    weak var delegate: WhatB?
}

Property 'delegate' with type 'WhatB?' cannot override a property with type 'WhatA?'

UIKit has no problems with the following

open class UIScrollView : UIView, NSCoding, UIFocusItemScrollableContainer {

    weak open var delegate: UIScrollViewDelegate?

}

open class UITableView : UIScrollView, NSCoding, UIDataSourceTranslating {

    weak open var delegate: UITableViewDelegate?

}

Why does this work in UIKit? The accepted answer for this question suggests this is not possible.

like image 484
Jonesy Avatar asked May 12 '19 05:05

Jonesy


People also ask

How do you invoke an overridden superclass method from a subclass?

It is what overriding for. The overridden method shall not be accessible from outside of the classes at all. But you can call it within the child class itself. to call a super class method from within a sub class you can use the super keyword.

Can we override class method in Swift?

Classes in Swift can call and access methods, properties, and subscripts belonging to their superclass and can provide their own overriding versions of those methods, properties, and subscripts to refine or modify their behavior.

When an overridden method is called from within a subclass it will always refer to the version of that method defined by the?

When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.

How do you override a method in Swift?

We use the override keyword to declare method overriding. For example, class Vehicle { func displayInfo(){ ... } } class Car: Vehicle { // override method override func displayInfo() { ... } }


1 Answers

The reason it works with UIScrollView and UITableView and their delegates is that they are generated Swift interfaces from the original Objective-C headers.

Objective-C lets you do this. While you can't create Swift classes that do this directly, Swift class interfaces generated from an Objective-C bridging header can result is the case you see here.

like image 151
rmaddy Avatar answered Oct 17 '22 00:10

rmaddy