The following documentation may be helpful: https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-ID122. You've probably already looked at that, but just in case. The following question may also help: Extending a Swift class with Objective C category.
As you know, to use Objective-C code in Swift there is the bridging header. To go the other way around, there is the auto-generated *-Swift.h
header that should be imported in .m
(and .mm
) implementation files. The documentation says it should not be imported into .h
files. In fact, the compiler won't let you import it into a .h
file that is included, directly or indirectly, in the bridging header. However, with some care you can import it into other .h
files.
Now, suppose your Swift class is called SwiftClass
and you want to add to it a method called ocFunction()
implemented in Objective-C. One approach, essentially presented in the aforementioned answer, is to implement a category in an Objective-C source file (.m
):
@implementation SwiftClass (OCExtension)
-(void)ocFunction {...}
@end
Then modify your SwiftClass
to include the following:
class SwiftClass : NSObject
{
...
@nonobjc func ocFunction()
{
self.perform(Selector(("ocFunction")))
}
...
}
The referenced answer suggests doing this in an extension, but since you have full control of the SwiftClass
source, you can just do it in the class directly. BTW, the Objective-C category function could be named something other than the SwiftClass
's function, thus eliminating the need for @nonobjc
.
Another approach might be to define an Objective-C wrapper interface like this:
@interface SwiftClassOC : NSObject
+(void)ocFunction:(SwiftClass*)sc;
@end
and make it available to Swift via the bridging header. The implementation would go into a .m
file. Then your ocFunction()
in SwiftClass
would look like
func ocFunction()
{
SwiftClassOC.ocFunction(self)
}
Please note that SwiftClassOC is stateless, so it's essentially a set of helper functions that take a SwiftClass
pointer. SwiftClass
is the one maintaining the state.