如何使用Implicitly Unwrapped Optionals?

use*_*425 5 swift

我正在将NSView移植到Swift,我需要使用Quartz CGContextAddPath.

import Cocoa

class MYView: NSView {

    init(frame: NSRect) {
        super.init(frame: frame)
    }

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)


        NSColor .redColor() .set()
        NSRectFill(self.bounds)
        var p :CGMutablePathRef = CGPathCreateMutable()
        var ctx =  NSGraphicsContext.currentContext().graphicsPort()
        CGContextAddPath(ctx, p) // compiler rejects this line

    }

}
Run Code Online (Sandbox Code Playgroud)

你怎么理解这个错误信息?

Cannot convert the expression's type 'Void' to type 'CGContext!'
Run Code Online (Sandbox Code Playgroud)

CGContextAddPath的Swift签名是:

func CGContextAddPath(context: CGContext!, path: CGPath!)
Run Code Online (Sandbox Code Playgroud)

我的错误是什么?

我用这个时:

let context = UnsafePointer<CGContext>(ctx).memory
Run Code Online (Sandbox Code Playgroud)

我现在有一个运行时错误:

Jun 3 15:57:13 xxx.x SwiftTest[57092] <Error>: CGContextAddPath: invalid context 0x7fff73bd0060. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

这是我目前使用的代码:

import Cocoa

class MYView: NSView {

    init(frame: NSRect) {
        super.init(frame: frame)
    }

    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        var p :CGMutablePathRef =  CGPathCreateMutableCopy( CGPathCreateWithRoundedRect(self.bounds, 10, 10, nil))
        var ctx =  NSGraphicsContext.currentContext().graphicsPort()
        let context = UnsafePointer<CGContext>(ctx).memory

        CGContextAddPath(context, p) // compiler no longer rejects this line
        var blueColor = NSColor.blueColor()
        CGContextSetStrokeColorWithColor(context, NSColor.blueColor().CGColor)
        CGContextSetLineWidth(context, 2)
        CGContextStrokePath(context)

    }

}
Run Code Online (Sandbox Code Playgroud)

use*_*425 10

截至Swift 1.0

如果您的部署目标是10.10,则可以使用Yosemite引入的便捷方法.

let context = NSGraphicsContext.currentContext().CGContext
Run Code Online (Sandbox Code Playgroud)

如果你必须支持10.9,你必须按照下面的方法手动转换上下文.

let contextPtr = NSGraphicsContext.currentContext().graphicsPort
let context = unsafeBitCast(contextPtr, CGContext.self)
Run Code Online (Sandbox Code Playgroud)