我有一個應用程序,我從Firebase獲取一些數據的天數,我試圖在單獨的圖表中顯示每天的數據,使用iOS圖表,但它崩潰時出現錯誤'致命錯誤:索引超出範圍'。下面是我的代碼:swift - iOS圖表 - 在一個ViewController中使用兩個數據集的兩個LineChart視圖
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Units Sold")
let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
firstDayChart.data = lineChartData
}
func setChart2(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Units Sold")
let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
secondDayChart.data = lineChartData
}
//按鈕
@IBAction func getResults(sender: UIButton) {
let doubleArray = BGdataOutsideDay1.map { Double($0)!}
// print(doubleArray)
// var newArray:[Double] = []
self.doublesArrayDay1 = doubleArray
if doublesArrayDay1.count != 0 {
let bgAvg = doubleArray.reduce(0, combine: +)/Double(doubleArray.count)
let highest = doubleArray.maxElement()
let lowest = doubleArray.minElement()
self.bgHighestDay1 = String(format: "%.1f", highest!)
self.bgAvgDay1 = String(format: "%.1f", bgAvg)
self.bgLowestDay1 = String(format: "%.1f", lowest!)
self.firstDayHighest.text = self.bgHighestDay1! + " " + "\(self.units!)"
self.firstDayAvg.text = self.bgAvgDay1! + " " + "\(self.units!)"
self.firstDayLowest.text = self.bgLowestDay1! + " " + "\(self.units!)"
} else {
self.firstDayHighest.text = "0" + " " + "\(self.units!)"
self.firstDayAvg.text = "0" + " " + "\(self.units!)"
self.firstDayLowest.text = "0" + " " + "\(self.units!)"
}
let doubleArray2 = BGdataOutsideDay2.map { Double($0)!}
// print(doubleArray)
// var newArray:[Double] = []
self.doublesArrayDay2 = doubleArray
if doublesArrayDay2.count != 0 {
let bgAvg2 = doubleArray2.reduce(0, combine: +)/Double(doubleArray.count)
let highest2 = doubleArray2.maxElement()
let lowest2 = doubleArray2.minElement()
self.bgHighestDay2 = String(format: "%.1f", highest2!)
self.bgAvgDay2 = String(format: "%.1f", bgAvg2)
self.bgLowestDay2 = String(format: "%.1f", lowest2!)
self.secondDayHighest.text = self.bgHighestDay2! + " " + "\(self.units!)"
self.secondDayAvg.text = self.bgAvgDay2! + " " + "\(self.units!)"
self.secondDayLowest.text = self.bgLowestDay2! + " " + "\(self.units!)"
} else {
self.secondDayHighest.text = "0" + " " + "\(self.units!)"
self.secondDayAvg.text = "0" + " " + "\(self.units!)"
self.secondDayLowest.text = "0" + " " + "\(self.units!)"
setChart(DateOutSideDay1, values: doublesArrayDay1)
setChart(DateOutSideDay2, values: doublesArrayDay2)
}
任何幫助將不勝感激!提前致謝! :)
好像'values'數組比'dataPoints'數組少。這會解釋你遇到的錯誤。 – Laffen
是的,我知道原因,但我想讓它工作:) – Deyan
你檢查了哪個數組導致這個問題? –