Swift protocol in Objective-C class

There are two common reasons for this occuring:

  1. Getting the module name wrong, see my answer.
  2. Having a circular reference – see mitrenegades answer below.

1. Get the module name right:

If both the swift protocol and and Objective C are in the same project then according to apple you should just need to make sure you get the correct module name.

For Xcode6 beta 5 you can find it under BuildSettings->Packaging->Product Module Name

A common mistake would be to think that each swift file/class gets its own file, but instead they are all put into one big one that is the name of the project.

A further mistakes are if the module name has spaces, these should be replaced with underscores.

Edit:

With your protocol I created a test project called ‘Test’ which compiles perfectly and it has the files:

TestObjClass.h

#import <Foundation/Foundation.h>
#import "Test-Swift.h"

@interface TestObjCClass : NSObject <SearcherProtocol>

@end

TestObjClass.m

#import "TestObjCClass.h"


@implementation TestObjCClass

@end

TestProtocol.swift

import Foundation

@objc protocol SearcherProtocol
{
    var searchNotificationTarget: SearchCompletedProtocol? { get }
    var lastSearchResults: [AnyObject] { get set }

    func search(searchParam: String, error: NSErrorPointer) -> Bool
}

@objc protocol SearchCompletedProtocol
{
    func searchCompletedNotification(sender: AnyObject!)
}

2. Avoid circular reference:

Mitrenegades answer explains this, but if your project needs to use the explicit objc class that uses the swift protocol, (rather than just using the protocol) then you will have circularity issues. The reason is that the swift protocol is defined to the swift-objc header, then to your obj-c class definition, which then goes again to the swift-objc header.

Mitrenegades solution is to use an objective-c protocol, is one way, but if you want a swift protocol, then the other would be to refactor the code so as to not use the objective-c class directly, but instead use the protocol (e.g. some protocol based factory pattern). Either way may be appropriate for your purposes.

Leave a Comment