苹果2015年WWDC面向协议编程Swift会话中的这行代码做了什么?
var draw: (CGContext)->() = { _ in () }
Swift 2.1版本的演示游乐场和使用这行代码的文件可以在这里找到:https://github.com/alskipp/Swift-Diagram-Playgrounds/blob/master/Crustacean.playground/Sources/CoreGraphicsDiagramView.swift
我正在尝试了解CGContextStrokePath(context)是如何被所有Drawables调用的。
它是一个带有闭包的属性(一个函数,或者更好:一个代码块,在本例中使用CGContext
作为参数)。它什么都不做。它忽略了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'
}