Swift & Obj-C Mix
I am not sure if I am doing target membership properly for the following HelloWorld example project.
The challenge I'm setting for myself is to setup the following two targets that consume the following mixture of Swift and objective-c.
Swift App target
-
Obj-C that consumes Swift.
-
Swift that consumes Obj-C.
Objective-C test target
- Obj-C that consumes Swift...which consumes Obj-C.
Is the following list of compile sources appropriate? Or is this working by accident?
final class Algorithm: NSObject {
@objc
func sortKey() -> Int {
let manager = PayloadManager() // PayloadManager is Obj-C and it consumes `APIClient` which is Swift.
return manager.fetch()
}
}
final class APIClient: NSObject {
@objc
func fetch() -> Int {
return 1
}
}
PayloadManager.h
#import <Foundation/Foundation.h>
@interface PayloadManager : NSObject
-(NSInteger)fetch;
@end
PayloadManager.m
#import "PayloadManager.h"
#import "HelloWorld-Swift.h" // must be hidden away in .m file
@implementation PayloadManager
-(NSInteger)fetch {
APIClient *client = [[APIClient alloc] init]; // APIClient is Swift
return [client fetch];
}
@end
HelloWorld-Bridging-Header.h
//
// Use this file to import your target's public headers that you would like to expose to Swift.
// HelloWorld-Bridging-Header.h
#import "PayloadManager.h"
HelloWorldTests-Bridging-Header.h
#ifndef HelloWorldTests_Bridging_Header_h
#define HelloWorldTests_Bridging_Header_h
// Can use either or here
//#import "HelloWorld-Bridging-Header.h"
#import "PayloadManager.h"
#endif /* HelloWorldTests_Bridging_Header_h */
Test
#import <XCTest/XCTest.h>
#import "HelloWorldTests-Swift.h" // Both Algorithm and APIClient are target members of test target
@interface APIClientTests : XCTestCase
@end
@implementation APIClientTests
- (void)testExample {
Algorithm *algorithm = [[Algorithm alloc] init];
NSInteger key1 = [algorithm sortKey];
APIClient *client = [[APIClient alloc] init];
NSInteger key2 = [client fetch];
XCTAssert(key1 == 1);
XCTAssert(key2 == 1);
}
@end