0

Apple 的 2015 年 WWDC 面向协议的 Swift 会议中的这行代码有什么作用?

var draw: (CGContext)->() = { _ in () }

可以在此处找到 Swift 2.1 版本的演示游乐场和使用此代码行的文件:https://github.com/alskipp/Swift-Diagram-Playgrounds/blob/master/Crustacean.playground/Sources/CoreGraphicsDiagramView。迅速

我试图了解如何为所有可绘制对象调用 CGContextStrokePath(context)。

4

1 回答 1

4

它是一个带有闭包的属性(一个函数,或者更好:一个代码块,CGContext在这种情况下将 a 作为参数)。它什么也不做。它忽略了CGContext(这就是_ in部分)。

稍后在示例中有此功能:

public func showCoreGraphicsDiagram(title: String, draw: (CGContext)->()) {
    let diagramView = CoreGraphicsDiagramView(frame: drawingArea)
    diagramView.draw = draw
    diagramView.setNeedsDisplay()
    XCPlaygroundPage.currentPage.liveView = diagramView
}

您可以在其中提供另一个闭包(CGContext) -> (),然后将此新闭包分配给该draw属性。

drawRect函数中它被调用:draw(context).

所以,基本上你可以提供一个绘制一些东西的代码块,例如

showCoreGraphicsDiagram("Diagram Title", draw: { context in
    // draw something using 'context'
})

甚至更短的“尾随闭包语法”:

showCoreGraphicsDiagram("Diagram Title") { context in
    // draw something using 'context'
}
于 2015-12-04T17:46:21.727 回答