Jonesy
Jonesy

Reputation: 305

Overriding superclass property with different type

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.

Upvotes: 8

Views: 584

Answers (1)

rmaddy
rmaddy

Reputation: 318874

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.

Upvotes: 8

Related Questions