英文:
How do I solve the "Unable to infer complex closure return type; add explicit type to disambiguate" error problem?
问题
以下是代码部分的中文翻译:
func drawChart(with data: [WAChartsView.Data], topChartOffset: Int) {
guard let maxValue = data.sorted(by: { $0.value > $1.value }).first?.value else { return }
let valuePoints = data.enumerated().map { CGPoint(x: CGFloat($0), y: CGFloat($1.value)) }
let chartHeight = bounds.height / CGFloat(maxValue + topChartOffset)
let points = valuePoints.map {
let x = bounds.width / CGFloat(valuePoints.count - 1) * $0.x //cgfl
let y = bounds.height - $0.y * chartHeight
return CGPoint(x: x, y: y)
}
}
请注意,我已将代码中的 >
更正为 >
,以使其在Swift代码中正常工作。如果您有任何其他疑问,请随时提出。
英文:
I made a function for drawing a graph and this error came up when creating points.
func drawChart(with data: [WAChartsView.Data], topChartOffset: Int) {
guard let maxValue = data.sorted(by: { $0.value > $1.value }).first?.value else { return }
let valuePoints = data.enumerated().map { CGPoint(x: CGFloat($0), y: CGFloat($1.value)) }
let chartHeight = bounds.height / CGFloat(maxValue + topChartOffset)
let points = valuePoints.map {
let x = bounds.width / CGFloat(valuePoints.count - 1) * $0.x //cgfl
let y = bounds.height - $0.y * chartHeight
return CGPoint(x: x, y: y)
}
}
The problem comes out after the line let points = valuePoints.map {
.
I found the same problems on the Internet, but they were mainly for SwiftUI.
答案1
得分: 0
The line let points = valuePoints.map {...}
is mapping from your source array, valuePoints
, to a new array. The compiler can't infer the type of the new array. I see this when the compiler can't infer the return type of a closure (which is what's happening here.)
Leo told you what to do: Declare the type of points
explicitly:
let points: [CGPoint] = valuePoints.map {...}
As Flanker says, the compiler will also generate this error when there is something else wrong with your code and it gets confused. Try the above and see what happens. (I don't see any other errors, but I also don't know the types of all the variables your code is using.)
英文:
The line let points = valuePoints.map {...}
is mapping from your source array, valuePoints
, to a new array. The compiler can't infer the type of the new array. I see this when the compiler can't infer the return type of a closure (which is what's happening here.)
Leo told you what to do: Declare the type of points
explicitly:
let points: [CGPoint] = valuePoints.map {...}
As Flanker says, the compiler will also generate this error when there is something else wrong with your code and it gets confused. Try the above and see what happens. (I don't see any other errors, but I also don't know the types of all the variables your code is using.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论