swift - 如何使用隐式解包选项?

标签 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

    }

}

您如何理解此错误消息?

Cannot convert the expression's type 'Void' to type 'CGContext!'

CGContextAddPath 的 Swift 签名是:

func CGContextAddPath(context: CGContext!, path: CGPath!)

我的错误是什么?

当我使用它时:

let context = UnsafePointer<CGContext>(ctx).memory

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

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)

    }

}

最佳答案

从 Swift 1.0 开始

如果您的部署目标是 10.10,您可以使用优胜美地引入的便捷方法。

let context = NSGraphicsContext.currentContext().CGContext

如果您必须支持 10.9,则必须按照以下方式手动转换上下文。

let contextPtr = NSGraphicsContext.currentContext().graphicsPort
let context = unsafeBitCast(contextPtr, CGContext.self)

关于swift - 如何使用隐式解包选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24016668/

相关文章:

ios - XCode 6 测试版 Swift,SpriteKit : Changing Deployment Target

ios - 带有 Soap Wcf Web 服务的 Swift ios

ios - swift UITableView 设置行宽

ios - Swift - 加载外部数据的可变范围

ios - SFSafariViewController 没有正确解除 (iOS 10.3)

XCode 7.3 - 工作区使用

ios - AdMob 原生高级广告单元 ID

ios - 在后台线程中动态更新 UILabel - Swift

xcode - Swift:如何为我的游戏添加地板?

swift - 如何在再次循环之前完成 SKAction