Matthew
Matthew

Reputation: 1396

How to correctly initialize an UnsafePointer in Swift?

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?

Upvotes: 23

Views: 13671

Answers (1)

Sulthan
Sulthan

Reputation: 130191

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).

Upvotes: 20

Related Questions