How to access a swift file from an objective file, while both of them are in Unit Test?

Viewed 29

This problem may still baffling many people, but there is no answer to this question yet.

I have 2 files, both are in the Unit Test directory.
1. A swift extension to NSError. Lets call it NSErrorExtension.swift. This extensions contains some static methods.
2. an objective C test class, lets call it UnitTest1.m .

Now, I want to access the static methods in NSErrorExtension.swift from UnitTest1.m. How do I do this? It just tells me that "No known class methods for selector...." I tried many solutions, none of them works.

1 Answers

Run into the same issue, seems the MyAppTests-Swift.h is not very "importable" :)

I had to resort to some not-so-nice workarounds to make this work. For class instantiation I used NSClassFromString() and then cast to a protocol visible on the Objective-C side. For your extension you could do something similar by declaring the methods in a header file, without actually implementing them.

So assuming your NSErrorExtension.swift extension looks like this:

extension NSError {
    @objc func someFunc() -> SomeResult
}

, you can create a NSErrorExtension.h file (without a corresponding .m one):

@interface NSError (UnitTestExtensions)
- (SomeResult *)someFunc;
@end

This should make the function available on the Objective-C side. The downside is that you'll need to do this for every function you want to expose from the Swift side of the unit tests.

Related