Search code examples
swiftuiviewcontrollerios-extensions

Unable to implement computed property override on UIViewController


When trying to implement this:

extension UIViewController {
    public var presentedViewController: UIViewController? {
        return UIViewController()
    }
}

I'm receiving the following error: .../ExampleApp/ExampleAppTests/SpecExtensions.swift:41:59: Getter for 'presentedViewController' with Objective-C selector 'presentedViewController' conflicts with method 'presentedViewController()' with the same Objective-C selector

I'm using the same selector that UIViewController.h defines: public var presentedViewController: UIViewController? { get }

Is the error misleading or am I just overlooking something? I've tried it with and without override, public, as a method, etc. No luck. However, I am able to override it if it's on a subclass of UIViewController, but not UIViewController itself.


Solution

  • The problem is that you have it in an extension. You can't override methods that were defined on a class from an extension. Basically an extension is not a sub-class, trying to redefine methods that exist on a class by implementing a new version in an extension will fail.

    Note that this works:

    class ViewController: UIViewController {
    
        override var presentedViewController: UIViewController? {
            return UIViewController()
        }
    
    }