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

回答1:

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
}


回答2:

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.