Can you override between extensions in Swift or not? (Compiler seems confused!)

只愿长相守 提交于 2019-11-27 07:58:23

It seems that overriding methods and properties in an extension works with the current Swift (Swift 1.1/Xcode 6.1) only for Objective-C compatible methods and properties.

If a class is derived from NSObject then all its members are automatically available in Objective-C (if possible, see below). So with

class A : NSObject { }

your example code compiles and works as expected. Your Code Data extension overrides work because NSManagedObject is a subclass of NSObject.

Alternatively, you can use the @objc attribute for a method or property:

class A { }

class B : A { }

extension A
{
    @objc var y : String { get { return "YinA" } }
}

extension B
{
   @objc override var y : String { get { return "YinB" } }
}

Methods which are not representable in Objective-C cannot be marked with @objc and cannot be overridden in a subclass extension. That applies for example to methods having inout parameters or parameters of an enum type.

I experienced this on Xcode9. Closing and reopening Xcode worked for me. Probably a bug in the compiler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!