I managed to create a NSProxy subclass in Objective-C that can be casted as its object type.
@interface ObjectProxy : NSProxy
@property (nonatomic, strong) id target;
- (instancetype)initWithTarget:(id)target;
@end
@implementation ObjectProxy
- (instancetype)initWithTarget:(id)target {
_target = target;
return self;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
return [_target methodSignatureForSelector:sel];
}
- (void)forwardInvocation:(NSInvocation *)invocation {
[invocation setTarget:_target];
[invocation invoke];
}
@end
In Swift I can use:
let myObject = MyObject()
let proxy = ObjectProxy(target: myObject)
let proxiedObject = proxy as? MyObject
Problem: When I use any subclass I created as target, I can't cast the proxy to the subclass type and only to the object type I subclassed:
class CustomView: NSView { }
let view = CustomView()
let proxy = ObjectProxy(target: view)
proxy as? CustomView // Fails
proxy as? NSView // Works
However casting a proxy of a subclass I create in Objective-C works:
@interface CustomView : NSView
@end
@implementation CustomView
@end
// Swift
let view = CustomView()
let proxy = ObjectProxy(target: view)
proxy as? CustomView // Works
I found this NSProxy dynamic casting to Swift or ObjC class behaves differently, but I'm unsure if it's related.