Swift doesn't see ObjC id<protocol> properties

I've got something along the lines of:

@protocol MyProtocol;
@interface MyClass: NSObject {
@property (readonly, retain, nullable) id<MyProtocol> proxy;

Swift can't see the proxy property, unless I remove the <MyProperty> part.

Am I doing something wrong, or is this well known? (I've been googling and searching and asking people for a bit, so I'm hoping I'm just doing something wrong.)

(Somewhat ironically, the protocol is defined in a Swift file.)

that's the crux of the issue. in swift define MyProtocol with @objc either as:

@objc protocol MyProtocol: AnyObject { ... }
or as:
@objc protocol MyProtocol: NSObjectProtocol { ... }

(doesn't matter which one)

1 Like

Yay! Thank you!

Weirdly, another protocol in the same .swift file has NSObjectProtocol, and I am not at all sure why. :grinning_face_with_smiling_eyes:

i think it'll work even without AnyObject / NSObjectProtocol. but @objc is important.

No, it had the @objc. It needed the inheritance apparently!

... I apparently spoke too soon. I can't get it working now, even with the NSObjectProtocol inheritance being specified. In my .swift file, I have:

@objc public protocol MyProtocol: NSObjectProtocol {
// stuff

In an objc .h file, I have:

@protocol MyProtocol;
// stuff, then an @interface
@property (retain, readonly, nullable) id<MyProtocol> proxy;

(If I comment out the <MyProtocol> text, it works -- and I apparently did that before, and forgot to undo it.)

And then in a .swift file, I have:

if let proxy = loader.proxy as? MyProtocol {

And then it tells me that loader has an element named proxy but it may not be available in this context, and the compiler says it doesn't exist at all, which was my original problem.

strange, it works for me... i'd recommend you distill this down into a minimal sample app - that will help to see where the problem is.

Ok, I've got a very-clumsy and minimal case for it. I don't know the best way to make it available, though.

Here is my horrible demonstration of my ignorance: GitHub - kithrup/BadSwiftExample: This is a (doomed to be short-lived) repo demonstrating a problem I am having with Swift and ObjC

perfect. just use instancetype instead of id:


(this forum soft thinks it's a diff :slight_smile:)

I actually had shared set up correctly in my real project, but not init. Changed them both in my stupid sample and it works.

I ... think I understand the compiler-logic there. Thanks again. :grinning_face_with_smiling_eyes:

Terms of Service

Privacy Policy

Cookie Policy