Swift扩展 - 方法与先前使用相同Objective-C选择器的声明冲突

Swa*_*nil 5 objective-c ios swift swift2

我正在开发iOS应用程序,它有Obj C代码以及Swift.我正在将现有的Objective C类别迁移到swift代码.但是当我在swift扩展中覆盖现有方法时,它没有编译.Swift扩展适用于新方法,但不适用于覆盖现有方法.

码:

extension UIViewController {


   public override func shouldAutorotate() -> Bool {
        return false
    }

    public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return UIInterfaceOrientationMask.Portrait
    }


}
Run Code Online (Sandbox Code Playgroud)

错误:

 Method 'shouldAutorotate()' with Objective-C selector 'shouldAutorotate' conflicts with previous declaration with the same Objective-C selector

 Method does not override any method from its superclass

 Method 'supportedInterfaceOrientations()' with Objective-C selector 'supportedInterfaceOrientations' conflicts with previous declaration with the same Objective-C selector
Run Code Online (Sandbox Code Playgroud)

在这里,我错过了什么?

我正在使用Xcode 7.3.1Swift 2.x

编辑:

从Answers下面,我知道我们不能像在Objective C Categories中那样在Swift扩展中改变运行时类的现有方法的行为.在这里,我应该创建一个将覆盖方法的基类,我应该使用我的所有ViewControllers作为新基类的子类作为父类.

但就我而言,我想改变所有"shouldAutorotate"方法的行为,包括第三方框架UIViewController.在上面的例子中,我不能强制所有第三方框架UIviewControllers成为我的基类的子类.在Objective C中,我可以做到这一点.

Tim*_*Tim 7

Swift扩展不能用于覆盖它们扩展的类中声明的方法 - 特别是对于Objective-C类,这非常类似于在同一个类中提供相同方法的两个定义.想象一下,看到一个看起来像这样的课程:

class UIViewController : UIResponder {
    public func shouldAutorotate() -> Bool {
        return true
    }
    public func shouldAutorotate() -> Bool {
        return false
    }
}
Run Code Online (Sandbox Code Playgroud)

哪一个获胜?这就是你被警告的冲突.

如果您需要覆盖您的视图控制器的方法,则需要在子类中执行此操作,而不是扩展.

Ninja编辑:这可能在Objective-C中可以做到,但那里是一个编程错误.如果类别与主类重复方法,则使用哪个定义是未定义的.请参阅此SO帖子支持Apple文档.