Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly initialize an UnsafePointer in Swift?

Tags:

I'm trying to use CTFontCreatePathForGlyph(font: CTFont?, glyph: CGGlyph, transform: CConstPointer<CGAffineTransform>):

let myFont = CTFontCreateWithName("Helvetica", 12, nil) let myGlyph = CTFontGetGlyphWithName(myFont, "a") let myTransform = CGAffineTransformIdentity 

But how do I correctly pass myTransform to CTFontCreatePathForGlyph?

I've tried creating a myTransformPointer to pass to the function like so:

var myTransformPointer: UnsafePointer<CGAffineTransform> = UnsafePointer().initialize(newvalue: myTransform) 

but I get this error:

Playground execution failed: error: <REPL>:20:76: error: '()' is not convertible to 'UnsafePointer<CGAffineTransform>' var myTransformPointer: UnsafePointer<CGAffineTransform> = UnsafePointer().initialize(newvalue: myTransform) 

so then I tried explicitly naming the type:

var myTransformPointer: UnsafePointer<CGAffineTransform> = UnsafePointer<CGAffineTransform>().initialize(newvalue: myTransform) 

and then I get a different error:

Playground execution failed: error: <REPL>:20:95: error: could not find an overload for 'init' that accepts the supplied arguments var myTransformPointer: UnsafePointer<CGAffineTransform> = UnsafePointer<CGAffineTransform>().initialize(newvalue: myTransform)                                                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 

The auto-complete suggests this should work?

like image 866
Matthew Avatar asked Jun 08 '14 20:06

Matthew


1 Answers

The simplest solution is using withUnsafePointer function:

let myFont = CTFontCreateWithName("Helvetica", 12, nil) let myGlyph = CTFontGetGlyphWithName(myFont, "a") var myTransform = CGAffineTransformIdentity  var path = withUnsafePointer(&myTransform) { (pointer: UnsafePointer<CGAffineTransform>) -> (CGPath) in     return CTFontCreatePathForGlyph(myFont, myGlyph, pointer) } 

The initialize is not a constructor. You would have to alloc a new memory using UnsafePointer<T>.alloc, then initialize and then dealloc. Function withUnsafePointer does that all for you.

Note that myTransform cannot be a constant (var not let) otherwise you cannot use it for an inout param (&myTransform).

like image 162
Sulthan Avatar answered Sep 18 '22 11:09

Sulthan