8

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.

Jonesy
  • 195
  • 8
  • You can not able to override in UIKit as well you can try it once more time – Ahemadabbas Vagh May 12 '19 at 06:32
  • @AhemadabbasVagh Can you please clarify your comment. – rmaddy May 12 '19 at 06:45
  • I suggest reading up on this topic here: https://forums.swift.org/t/in-a-sub-class-is-it-possible-to-override-a-property-of-the-super-class-and-constrain-to-a-sub-type-of-the-original-property/10747 . TL;DR: It's unsafe Objective-C magic that you can't do in Swift. – TylerP May 12 '19 at 06:46
  • Thanks @TylerTheCompiler will accept if made official answer. – Jonesy May 12 '19 at 06:48
  • Thanks, but I didn't want to post it as an answer because it was just a link. @rmaddy 's answer actually explains it, which is better. – TylerP May 12 '19 at 06:58

1 Answers1

8

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 3
    Adding the link provided by @TylerTheCompiler in comments for completion https://forums.swift.org/t/in-a-sub-class-is-it-possible-to-override-a-property-of-the-super-class-and-constrain-to-a-sub-type-of-the-original-property/10747/5 – Jonesy May 12 '19 at 06:53