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.
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.
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 subclass. The version of the method defined by the superclass will be hidden.
We use the override keyword to declare method overriding. For example, class Vehicle { func displayInfo(){ ... } } class Car: Vehicle { // override method override func displayInfo() { ... } }
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.
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