在 Swift 中使用 NSProxy

Ric*_*hiy 8 proxy-pattern nsproxy swift

如何NSProxy在 Swift 中创建子类?

尝试添加任何init方法都会失败并出现错误:“无法在初始化程序之外调用超级初始化”或“从初始化程序返回之前,不会在所有路径上调用超级初始化”

错误1 错误2

使用 Objective-C 子类作为基类是可行的,但感觉更像是一种 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()
  }
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*ter 1

简单的解决方案:创建继承自 NSProxy 的 Objective-C 类,然后从中继承 Swift 类。

我的 GitHub 上的示例:https://gist.github.com/SoundBlaster/0e53bae4ab814537c5868564d95eb553

// Objective-C Header BaseProxyForSwift.h

NS_ASSUME_NONNULL_BEGIN

NS_SWIFT_NAME(BaseProxyForSwift)
@interface BaseProxyForSwift : NSProxy

+ (id)with:(id)object;

@end

NS_ASSUME_NONNULL_END
Run Code Online (Sandbox Code Playgroud)
// Objective-C Implementation BaseProxyForSwift.m

#import "BaseProxyForSwift.h"

@interface BaseProxyForSwift ()
@property (nonatomic, strong) id object;
@end

@implementation BaseProxyForSwift

+ (id)with:(id)object {
    BaseProxyForSwift *res = [self alloc];
    res.object = object;
    return res;
}

@end
Run Code Online (Sandbox Code Playgroud)
// Swift Implementation BaseSwiftProxy.swift

import Foundation

public class BaseSwiftProxy: BaseProxyForSwift {}
Run Code Online (Sandbox Code Playgroud)
// Usage in Swift

let a = NSObject()
let p = BaseSwiftProxy.with(a)
Run Code Online (Sandbox Code Playgroud)

如果您要在一个项目中混合使用多种语言,请不要忘记 Objective-C 桥接标头:https://developer.apple.com/documentation/swift/importing-objective-c-into-swift