4

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

4
  • 2
    Shouldn't it return a boolean? Commented Aug 5, 2015 at 12:12
  • No. Function in Swift class was autocompleted by xcode. Also see documentation Commented Aug 5, 2015 at 12:18
  • So you are using Swift 2.0? Commented Aug 5, 2015 at 12:19
  • func buyFavoriteSnack(exception: bool) throws In the implementing class func buyFavoriteSnack(exception: bool) throws { let snackName = favoriteSnacks[person] ?? "Candy Bar" try vend(itemNamed: snackName) } Or simply refer developer.apple.com/library/prerelease/ios/documentation/Swift/… Commented Aug 5, 2015 at 12:25

2 Answers 2

6

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Both solutions works. Thank you. Although Solution 1 is a bit weird, because according to documentation suffix WithError should work too.
@Joey: I assume that the rules are slightly different for protocol methods. Here the Swift method is mapped to Objective-C (to check the conformance), not the other way around.
The problem for me was that I misspelled the name of the method in terms of lower and uppercase. Something like: - (void) thisClass:(Class *)class DidSendStuff:(Stuff *)stuff and I was trying to work with - (void) thisClass:(Class *)class didSendStuff:(Stuff *)stuff notice the lower and uppercase of DID SEND STUFF
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.