Re: Swift 2 init() with CF types and throws
Re: Swift 2 init() with CF types and throws
- Subject: Re: Swift 2 init() with CF types and throws
- From: Marco S Hyman <email@hidden>
- Date: Wed, 01 Jul 2015 16:59:17 -0700
> class
> Context
> {
> init()
> throws
> {
> let cocoaCTX = NSGraphicsContext.currentContext()
> guard let sysCTX = cocoaCTX.graphicsPort as! CGContextRef else { throw Errors.InvalidContext }
> CGContext = sysCTX;
> }
>
> var CGContext : CGContextRef
> }
You can’t do that. The CGContext variable MUST be initialized before you
can throw, even in a failable initializer (which this isn’t). It’s a current
shortcoming of the language. That is likely causing some of the errors you
are seeing.
Something like this works (Xcode 7)
if let currentContext = NSGraphicsContext.currentContext() {
var context: CGContext! = nil
// 10.9 doesn't have CGContext
if #available(OSX 10.10, *) {
context = currentContext.CGContext
} else {
// graphicsPort is type UnsafePointer<()>
context = unsafeBitCast(currentContext.graphicsPort,
CGContext.self)
}
// do something with context
}
That’s not an initializer, but the point is you can’t guarantee that the
context won’t wind up nil and must account for that. Also, I found when
using graphicsPort on 10.9 (this code originally predated Swift 2) the
unsafeBitCast was necessary to get a working value of context. Using
the currentContext.CGContext property is so much easier.
Marc
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden