【问题标题】:Swift 2.2 and NSProxy. How can I use it?斯威夫特 2.2 和 NSProxy。我该如何使用它?
【发布时间】:2016-04-07 14:06:53
【问题描述】:

NSProxy的接口是

public class NSProxy : NSObjectProtocol {
    public class func alloc() -> Self
    public class func `class`() -> AnyClass
    public func forwardInvocation(invocation: NSInvocation)
    public func dealloc()
    public func finalize()
    public var description: String { get }
    public var debugDescription: String { get }
    public class func respondsToSelector(aSelector: Selector) -> Bool
}

所以它没有任何初始化程序。但是 Swift 编译器需要从子类的初始化器中调用 Super.init。

在从初始化程序返回之前,不会在所有路径上调用 Super.init

class SimpleDecorator: NSProxy {
    let phone: Phone
    init(phone: Phone) { // compile error with Super.init
        self.phone = phone
    }
}

我没有把它放在对super的调用中,它不会编译,但是当然由于NSProxy没有init,所以当我调用super.init()时它不会编译。

在 Swift 中是否可以有一个 NSProxy 的子类?

【问题讨论】:

  • 似乎是一个已知问题:openradar.me/18548454.
  • DateOriginated:04-Oct-2014 03:58PM 也许苹果修复了它。我试图通过扩展将初始化程序添加到 NSProxy,但它不起作用。

标签: swift


【解决方案1】:

NSProxy 是一个抽象类。关于 NSProxy 的 Apple 文档说:“一个抽象超类,为充当其他对象或尚不存在的对象的替代对象的对象定义 API”。

关于维基百科抽象类的文档说:

在支持继承的语言、抽象类或 抽象基类(ABC),是一个不能被实例化的类 因为它要么被标记为抽象,要么只是指定 抽象方法(或虚拟方法)。


为抽象类调用 super.init() 是错误的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-22
    • 2017-03-24
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 2018-02-13
    相关资源
    最近更新 更多