简体   繁体   中英

Cannot adopt a swift class to an objective C protocol of type X <NSObject>

I am very new to Swift and so I may phrase things weirdly here. Apologies!

I've got the following (simplified) protocol in Objective C:

@protocol OtherProtocol <NSObject>
@optional

...

@end

I would like to create a class in Swift (4.2) that adheres to this protocol, so I defined my class like:

class MyClass : OtherProtocol {

}

Naturally, XCode will complain because my class doesn't have the correct methods.

It looks like I need to implement a bunch of NSObject methods in addition to those defined in OtherProtocol . When XCode adds in the missing method stubs from NSObject , there's one in particular giving issues:

func `self`() -> Self {
    ...
}

The problem with this method is Method cannot be an implementation of an @objc requirement because its result type cannot be represented in Objective-C .

I'd like the quickest way out of this, as I won't end up using any of those standard NSObject functions anyways. Any thoughts?

Actually, there is no need to implement NSObject's methods. To be able to subclass/inherit from Objective-C classes/protocols you just need to inherit from NSObject. This is to make sure that your Swift class can be used in Objective-C environment as well. Also, Swift structs can't adopt Objective-C protocols, as there is no such type in Obj-C

This should work

class MyClass: NSObject, OtherProtocol {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM