【问题标题】:WWDC Protocol-Oriented Programming in Swift sessionWWDC Swift 会话中面向协议的编程
【发布时间】:2015-12-04 17:26:32
【问题描述】:

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

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

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

我试图了解如何为所有 Drawable 调用 CGContextStrokePath(context)。

【问题讨论】:

    标签: swift wwdc


    【解决方案1】:

    它是一个带有闭包的属性(一个函数,或者更好:一个代码块,在这种情况下将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'
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      相关资源
      最近更新 更多