如何在Swift中正确初始化UnsafePointer?

时间:2014-06-08 20:59:48

标签: swift

我正在尝试使用CTFontCreatePathForGlyph(font: CTFont?, glyph: CGGlyph, transform: CConstPointer<CGAffineTransform>)

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

但我如何正确地将myTransform传递给CTFontCreatePathForGlyph

我尝试创建myTransformPointer以传递给函数,如下所示:

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

但是我收到了这个错误:

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

然后我尝试明确命名类型:

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

然后我得到一个不同的错误:

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)
                                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

自动完成表明这应该有用吗?

1 个答案:

答案 0 :(得分:17)

最简单的解决方案是使用withUnsafePointer函数:

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

initialize不是构造函数。您必须alloc使用UnsafePointer<T>.alloc,然后initialize然后dealloc withUnsafePointer新记忆。函数myTransform为您完成所有这些。

请注意,var不能是常量(let而不是inout),否则您无法将其用于&myTransform参数({{1}})。