How to correctly initialize an UnsafePointer in Swift?

前端 未结 1 1928
不知归路
不知归路 2021-02-01 05:54

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

let myFont = CTFontCr         


        
相关标签:
1条回答
  • 2021-02-01 06:19

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

    0 讨论(0)
提交回复
热议问题