How to use implicitly disabled options?

I am migrating NSView to Swift and I need to use 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 } } 

How do you understand this error message?

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

Swift Signature for CGContextAddPath:

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

What is my mistake?

When I use this:

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

I now have a runtime error:

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.

Here is the code I'm using now:

 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) } } 
+5
swift
source share
2 answers

Starting with Swift 1.0

If the deployment target is 10.10, you can use the convenience method introduced with Yosemite.

 let context = NSGraphicsContext.currentContext().CGContext 

If you need to support 10.9, you will have to manually use the context as shown below.

 let contextPtr = NSGraphicsContext.currentContext().graphicsPort let context = unsafeBitCast(contextPtr, CGContext.self) 
+10
source share

Use NSGraphicsContext.currentContext().graphicsPort() . It returns void *. You must give it to CGContextRef

 let ctx = UnsafePointer<CGContext>(NSGraphicsContext.currentContext().‌​graphicsPort()).memo‌​ry 
+1
source share

All Articles