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

前端之家收集整理的这篇文章主要介绍了如何在Swift中正确初始化UnsafePointer?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用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)
                                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

自动完成建议这应该工作?

最简单的解决方案是使用withUnsafePointer函数
let myFont = CTFontCreateWithName("Helvetica","a")
var myTransform = CGAffineTransformIdentity

var path = withUnsafePointer(&myTransform) { (pointer: UnsafePointer<CGAffineTransform>) -> (CGPath) in
    return CTFontCreatePathForGlyph(myFont,myGlyph,pointer)
}

初始化不是构造函数。您将不得不使用UnsafePointer< T> .alloc分配一个新内存,然后初始化然后释放。功能withUnsafePointer为您做的一切。

请注意,myTransform不能是常量(var not let),否则不能将其用于inout参数(& myTransform)。

原文链接:https://www.f2er.com/swift/320388.html

猜你在找的Swift相关文章