[英]How to correctly initialize an UnsafePointer in Swift?
I'm trying to use CTFontCreatePathForGlyph(font: CTFont?, glyph: CGGlyph, transform: CConstPointer<CGAffineTransform>)
: 我正在尝试使用
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
? 但是如何正确地将
myTransform
传递给CTFontCreatePathForGlyph
?
I've tried creating a myTransformPointer
to pass to the function like so: 我已经尝试创建一个
myTransformPointer
来传递给函数,如下所示:
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? 自动完成表明这应该有效吗?
The simplest solution is using withUnsafePointer
function: 最简单的解决方案是使用
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)
}
The initialize
is not a constructor. initialize
不是构造函数。 You would have to alloc
a new memory using UnsafePointer<T>.alloc
, then initialize
and then dealloc
. 你将不得不
alloc
使用新的存储UnsafePointer<T>.alloc
,然后initialize
,然后dealloc
。 Function withUnsafePointer
does that all for you. 函数
withUnsafePointer
为您完成所有这些。
Note that myTransform
cannot be a constant ( var
not let
) otherwise you cannot use it for an inout
param ( &myTransform
). 请注意,
myTransform
不能是常量( var
not let
),否则你不能将它用于inout
param( &myTransform
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.