0

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.

Stefan
  • 5,203
  • 8
  • 27
  • 51
solidcell
  • 7,639
  • 4
  • 40
  • 59

1 Answers1

1

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()
    }

}
Daniel T.
  • 32,821
  • 6
  • 50
  • 72
  • Why does this work then?: class ViewControllerSubclass: UIViewController { } extension ViewControllerSubclass { override var presentedViewController: UIViewController? { return UIViewController() } } – solidcell Nov 14 '15 at 21:21
  • I'm having the hardest time getting code to format in my response above. Maybe it's not possible; Sorry it's so hard to read. – solidcell Nov 14 '15 at 21:23
  • No problem... That works because you have the extension in the same file in which the class is defined, so the compiler treats it as part of the `class`. If you move that extension to a separate file, it won't compile either. – Daniel T. Nov 14 '15 at 21:24
  • It's actually still working if I move the extension to a different file. – solidcell Nov 14 '15 at 21:27
  • Sorry, my first explanation was wrong... Put it in both your sub-class and the extension. Then it won't work. You can't use extensions to override methods that already exist in a class. `presentedViewController` already exists in `UIViewController`. Since you didn't define it in `ViewControllerSubclass` you were able to override it in the extension. – Daniel T. Nov 14 '15 at 21:36
  • Fixed answer with better explanation. – Daniel T. Nov 14 '15 at 21:51