Swift class does not conform to Objective-C protoc

2020-02-14 04:30发布

I have Objective-C Protocol

@protocol SomeObjCProtocol
- (BOOL) doSomethingWithError: (NSError **)error;
@end

And Swift class

class SwiftClass : SomeObjCProtocol
{
    func doSomething() throws {    
    }
}

Compilers gives me an error

Type 'SwiftClass' does not conform to protocol 'SomeObjCProtocol'"

Is there any solution how to get rid of this error? I'm using XCode 7 Beta 4

2条回答
在下西门庆
2楼-- · 2020-02-14 04:53

When encountering that error message, one source of the problem might be that the Swift class conforming to the Objetive C protocol was not inherited from NSObject.

查看更多
等我变得足够好
3楼-- · 2020-02-14 05:07

There are two problems:

  • Swift 2 maps func doSomething() throws to the Objective-C method - (BOOL) doSomethingAndReturnError: (NSError **)error;, which is different from your protocol method.
  • The protocol method must be marked as "Objective-C compatible" with the @objc attribute.

There are two possible solutions:

Solution 1: Rename the Objective-C protocol method to

@protocol SomeObjCProtocol
- (BOOL) doSomethingAndReturnError: (NSError **)error;
@end

Solution 2: Leave the Objective-C protocol method as it is, and specify the Objective-C mapping for the Swift method explicitly:

@objc(doSomethingWithError:) func doSomething() throws {
    // Do stuff
}
查看更多
登录 后发表回答