Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C test class using Swift code

I have a swift protocol IModelIdProvider in the MyProjectName folder. I have created an objective-c unit test class named RemoteModelFactoryTest in the MyProjectNameTests folder. To do some tests, RemoteModelFactoryTest must implement the IModelIdProvider protocol.

When I #import "MyProjectName-Swift.h" to use my swift protocol in my objective-c class, I get a file not found.

If I change the #import instruction to #import "MyProjectNameTests-Swift.h", the header is found but not my protocol (it's defined in the MyProjectName project, not in the MyProjectNameTests project).

Is there something special to do in the *Tests projects to use Swift code ?

like image 215
Morniak Avatar asked Jun 23 '14 14:06

Morniak


People also ask

Can we use Swift code in Objective-C?

You can work with types declared in Swift from within the Objective-C code in your project by importing an Xcode-generated header file. This file is an Objective-C header that declares the Swift interfaces in your target, and you can think of it as an umbrella header for your Swift code.

Can Objective-C class inherit from Swift class?

Unfortunately, it's not possible to subclass a Swift class in Objective-C. Straight from the docs: You cannot subclass a Swift class in Objective-C.

How do I add Swift class to Objective-C project?

To access and use swift classes or libraries in objective-c files start with an objective-c project that already contains some files. Add a new Swift file to the project. In the menu select File>New>File… then select Swift File, instead of Cocoa Touch Class. Name the file and hit create.


1 Answers

I know its extra hacky and everything, but what I did and it worked was to copy public headers from generated "Project-Swift.h" and paste whats needed to .m file of test.

So I copied something like this:

SWIFT_CLASS("_TtC10Inventorum11ImageEntity")
@interface ImageEntity : NSObject <FICEntity>
@property (nonatomic, copy) NSString * imageID;
@property (nonatomic) NSURL * retinaImageURL;
@property (nonatomic) NSURL * nonRetinaimageURL;
@property (nonatomic, readonly) NSURL * imageURL;
@property (nonatomic, readonly, copy) NSString * UUID;
@property (nonatomic, readonly, copy) NSString * sourceImageUUID;
@property (nonatomic) RACSignal * rac_signalForImage;
- (instancetype)init OBJC_DESIGNATED_INITIALIZER;
- (NSURL *)sourceImageURLWithFormatName:(NSString *)formatName;
- (FICEntityImageDrawingBlock)drawingBlockForImage:(UIImage *)image withFormatName:(NSString *)formatName;
- (void)objc_setType:(NSString *)type;
@end

And on top of this I have also copied all the macros for SWIFT_CLASS etc. My tests are building and passing testing Swift code.

BTW. Dont forget to put public on tested classes and methods in Swift.

like image 86
Bartosz Hernas Avatar answered Sep 26 '22 13:09

Bartosz Hernas