在 Swift 4.1 中使用 NSProxy

Use NSProxy in Swift 4.1

如何在 Swift 中创建 NSProxy subclass?

尝试添加任何 init 方法失败并出现错误: "Super init can't be called outside of the initializer",或 "Super init isn't called on all paths before returning from initializer"

使用 Objective-C subclass 作为基础 class 可行,但感觉更像是 hack:

// Create a base class to use instead of `NSProxy`
@interface WorkingProxyBaseClass : NSProxy
- (instancetype)init;
@end

@implementation WorkingProxyBaseClass
- (instancetype)init
{
  if (self) {

  }
  return self;
}
@end



// Use the newly created Base class to inherit from in Swift
import Foundation

class TestProxy: WorkingProxyBaseClass {
  override init() {
    super.init()
  }
}

NSProxy 是抽象的class。关于 NSProxy 的 Apple 文档说 "An abstract superclass defining an API for objects that act as stand-ins for other objects or for objects that don’t exist yet".

关于维基百科摘要 class 的文档说:

In a language that supports inheritance, an abstract class, or abstract base class (ABC), is a class that cannot be instantiated because it is either labeled as abstract or it simply specifies abstract methods (or virtual methods).

Calling super.init() 对于摘要 class 是错误的。 在第二个 class 中,您不是为抽象 class 调用 super.init(),而是为具体 class 调用 WorkingProxyBaseClass。在 Objective c 中你没有调用 [super init] 因此代码正在运行。