Is there any way to use swift library in objc project via Carthage?
Once you have added the Charts.framework to the Embedded Binaries in your project settings, you can import Swift code into ObjC as follows. For example, with a sample project named ChartsObjCSample
, you need to:
import "ChartsObjCSample-Swift.h"
Now you should be able to use the Charts API in your ObjC code.
However, at times the above -Swift.h
file is not created, in which case you can create a dummy Swift file, add the brining header as per Xcode instructions and then clean, build again, which should create the -Swift.h
file.
Finally, to use the Charts API for example to create a BarChart, you can have a ViewController with the storyboard view class assigned as BarChartView
as shown below.
Then the view controller can render a BarChart with some code like this:
#import "ViewController.h"
#import "ChartsObjCSample-Swift.h"
@import Charts;
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
BarChartView* barChartView = (BarChartView*)self.view;
NSMutableArray* dataEntries = [[NSMutableArray alloc] init];
for(int i = 0; i < 100; i++) {
BarChartDataEntry* dataEntry = [[BarChartDataEntry alloc] initWithX:5.0 * arc4random_uniform(12) y:100.0];
[dataEntries addObject:dataEntry];
}
BarChartDataSet* dataSet = [[BarChartDataSet alloc] initWithValues:dataEntries label:@"Visitor Count"];
BarChartData* barChartData = [[BarChartData alloc] initWithDataSet:dataSet];
barChartView.data = barChartData;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
The screenshot of the rendered bar chart:
The above sample code is available on GitHub here.
From apple docs:
To import Swift code into Objective-C from the same target
Import the Swift code from that target into any Objective-C .m file within that target using this syntax and substituting the appropriate name:
#import "ProductModuleName-Swift.h"