0

What does this line of code from Apple's 2015 WWDC Protocol-Oriented Programming in Swift session do?

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

A Swift 2.1 version of the demo playground and file where this line of code is used can be found here: https://github.com/alskipp/Swift-Diagram-Playgrounds/blob/master/Crustacean.playground/Sources/CoreGraphicsDiagramView.swift

I am trying to understand how CGContextStrokePath(context) is getting called for all of the Drawables.

tonethar
  • 2,112
  • 26
  • 33

1 Answers1

4

It's a property with a closure (a function, or better: a code block, taking a CGContext as argument in this case). It does nothing. It ignores the CGContext (that's the _ in part).

Later in the example there's this function:

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

where you can provide another closure (CGContext) -> (), then this new closure is assigned to the draw property.

And in the drawRect function it's invoked: draw(context).

So, basically you can provide a code block that draws something, for example

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

or even shorter with the "trailing closure syntax":

showCoreGraphicsDiagram("Diagram Title") { context in
    // draw something using 'context'
}
jabu.10245
  • 1,884
  • 1
  • 11
  • 20