我正在尝试使用'weights'数组来填充下面的获取请求图表。但我收到错误“无法使用'NSNumber'类型的参数调用'init',我不知道为什么。'weights'数组应该是一个UInt16数组。
var weights : [Int16] = []
func weightFetchRequest() -> NSFetchRequest {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "Assessment")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "nsDateOfAssessment", ascending: true)]
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [Assessment]?
if let assessments = fetchedResults {
let weightss = assessments.map { assessment in assessment.weight }
weights = weightss
println(weights)
println(weightss)
}
return fetchRequest
}
func lineChartView(lineChartView: JBLineChartView!, verticalValueForHorizontalIndex horizontalIndex: UInt, atLineIndex lineIndex: UInt) -> CGFloat {
if (lineIndex == 0) {
return CGFloat(weights[Int16(horizontalIndex)] as NSNumber) //Error here
}
return 0
}
答案 0 :(得分:1)
行中有两个问题
return CGFloat(weights[Int16(horizontalIndex)] as NSNumber)
weights[Int16(horizontalIndex)]
无法编译,因为Int16
不能是数组下标。它应该是weights[Int(horizontalIndex)]
。weights[...] as NSNumber
无法编译,因为固定大小整数类型与NSNumber
之间没有自动桥接,
它应该是NSNumber(short: weights[...])
。所以这将编译和工作:
return CGFloat(NSNumber(short: weights[Int(horizontalIndex)]))
但是,不需要在它们之间使用NSNumber
,它可以
简化为
return CGFloat(weights[Int(horizontalIndex)])