Stored Properties don't always override a protocol extension

Hi,


I thought overriding the default implementation of a protocol extension in a subclass works like overriding a method. Instead, methods don't take into account the overridden implementations of the subclass. It's a bit complicated, so here's an example:

import UIKit
protocol MyProtocol {
    var myProperty: String? { get }
}
extension MyProtocol where Self: UIViewController {
    var myProperty: String? {
        return "This comes from the Extension"
    }
}
extension UIViewController: MyProtocol {
    func whatIsMyProperty() -> String? {
        return myProperty
    }
}
class SpecialViewController: UIViewController {
    var myProperty: String?
   
    func whatIsMyProperty2() -> String? {
        return myProperty
    }
}
let viewController = SpecialViewController()

viewController.myProperty //nil
viewController.myProperty = "I set this"
viewController.myProperty // "I set this"
viewController.whatIsMyProperty()  // "This comes from the Extension"
viewController.whatIsMyProperty2()  // "I set this"


To me this is very counter intuitive. Can I access the new stored property somehow in whatIsMyProperty() in UIViewController without adding anything but the stored property itself to the subclass?


Thanks!

Gernot.

Answered by GSnyder in 68673022

This has been coming up a lot, in various guises. Protocol extensions are just compile-time syntactic sugar. They don't create any actual hierarchy or overridable relationship.

Accepted Answer

This has been coming up a lot, in various guises. Protocol extensions are just compile-time syntactic sugar. They don't create any actual hierarchy or overridable relationship.

Stored Properties don't always override a protocol extension
 
 
Q