关于闭包的SWIFT语法问题

问题描述 投票:0回答:1

也许有人会很友善地向我解释这个片段

raywenderlich上有关于Core Graphics的很好的教程。不幸的是,该页面上的评论已关闭

作者声明

//Weekly sample data
var graphPoints = [4, 2, 6, 4, 5, 8, 3]

注意graphPoints末尾的“ s”。然后,要计算带有此类数字的图表的y坐标,他在闭包内使用了graphPoint(末尾没有“ s”)。尽管如此,代码的运行对我来说还是不错的。

// calculate the y point

let topBorder = Constants.topBorder
let bottomBorder = Constants.bottomBorder
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints.max()!
let columnYPoint = { (graphPoint: Int) -> CGFloat in
  let y = CGFloat(graphPoint) / CGFloat(maxValue) * graphHeight
  return graphHeight + topBorder - y // Flip the graph
}

而且此项目中没有进一步使用graphPoint(我知道,使用“ find”)。所以我想知道,如何将带有“ s”的graphPoints链接到columnYPoint。

尽管我目前不知道y值如何流入闭包,但让我已经扩展了我的问题:如果我的值位于结构为[[x1,x2],[y1,y2]的2D数组中,我可以只将我的y(或仅我的x)值传递给此闭包吗?

干杯!

更新之后,这就是使用columnYPoint绘制图形的方式:

// draw the line graph

UIColor.white.setFill()
UIColor.white.setStroke()

// set up the points line
let graphPath = UIBezierPath()

// go to start of line
graphPath.move(to: CGPoint(x: columnXPoint(0), y: columnYPoint(graphPoints[0])))

// add points for each item in the graphPoints array
// at the correct (x, y) for the point
for i in 1..<graphPoints.count {
  let nextPoint = CGPoint(x: columnXPoint(i), y: columnYPoint(graphPoints[i]))
  graphPath.addLine(to: nextPoint)
}
graphPath.stroke()
swift closures core-graphics
1个回答
0
投票

如您所知,这是一个闭包(放入名为columnYPoint的变量,并为其命名):

let columnYPoint = { (graphPoint: Int) -> CGFloat in
  let y = CGFloat(graphPoint) / CGFloat(maxValue) * graphHeight
  return graphHeight + topBorder - y // Flip the graph
}

实际上,这就像一个名为columnYPoint的函数:

func columnYPoint(_ graphPoint: Int) -> CGFloat {
    let y = CGFloat(graphPoint) / CGFloat(maxValue) * graphHeight
    return graphHeight + topBorder - y // Flip the graph
}

作者为什么编写一个闭包并将其放入变量中,而不是编写函数?我不知道,因为我看不懂头脑。这是作者的风格选择。

[如果您查看它的调用方式,则此函数/闭包将根据给定的钢筋高度graphPoint计算钢筋的Y坐标。 graphPoint是函数的参数,因此当然在其余代码中不会使用它。您可以从呼叫者那里看到:

graphPath.move(to: CGPoint(x: columnXPoint(0), y: columnYPoint(graphPoints[0])))
// and
let nextPoint = CGPoint(x: columnXPoint(i), y: columnYPoint(graphPoints[i]))

columnYPoint将为graphPoints中的每个元素调用,因此graphPoint将为graphPoints中的每个值。毕竟,我们需要计算每个条的坐标。

[似乎也有前面提到的columnYPoint闭包,它在给定的条形索引下计算X坐标。您可以将这两个闭包组合在一起,以得到一个闭包,从而给您一个CGPoint

let margin = Constants.margin
let graphWidth = width - margin * 2 - 4
let topBorder = Constants.topBorder
let bottomBorder = Constants.bottomBorder
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints.max()!
let columnPoint = { (column: Int, graphPoint: Int) -> CGPoint in
    //Calculate the gap between points
    let spacing = graphWidth / CGFloat(self.graphPoints.count - 1)
    let x = CGFloat(column) * spacing + margin + 2
    let y = CGFloat(graphPoint) / CGFloat(maxValue) * graphHeight
    return CGPoint(x: x, y: graphHeight + topBorder - y) // Flip the graph
}
© www.soinside.com 2019 - 2024. All rights reserved.