fadfad fadfad - 21 days ago 6
Objective-C Question

NSArray element failed to match the Swift Array Element type - Objective-C With Swift Library (Charts)

I'm using the iOS charts library, and I'm encountering the following error message:


fatal error: NSArray element failed to match the Swift Array Element type


I'm trying to implement a line graph with the following Objective-C code:

NSMutableArray *dataSets = [[NSMutableArray alloc] init];
set1 = [[LineChartDataSet alloc] initWithValues:yVals];
[dataSets addObject:set1];
LineChartData *data = [[LineChartData alloc] initWithDataSets:dataSets];
_chartView.data = data;


The error is occuring on this line within the ChartViewBase.swift file.

for set in _data!.dataSets


_data
is a
ChartData
object and
dataSets
is a
[IChartDataSet]
Swift Array.

What is a workaround for working with Swift arrays in Objective-C?

Answer

Do as follow.

    NSMutableArray *xVals = [[NSMutableArray alloc] init];
    for (int i = 0; i <dataPoints.count; i++)
      {
        [xVals addObject:[dataPoints objectAtIndex:i]];
      }

    NSMutableArray *yVals = [[NSMutableArray alloc] init];        
    for (int i = 0; i < values.count; i++)
    {
        int val = [([values objectAtIndex:i])intValue];
        [yVals addObject:[[ChartDataEntry alloc] initWithValue:(int)val xIndex:i]];
    }

    LineChartDataSet *set1 = nil;
    set1 = [[LineChartDataSet alloc] initWithYVals:yVals label:@""];

    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    [dataSets addObject:set1];
    LineChartData *data = [[LineChartData alloc] initWithXVals:xVals dataSets:dataSets];
   lineChart.data = data;