How do you alloc/dealloc unsafe pointers in Swift?

后端 未结 4 1589
我寻月下人不归
我寻月下人不归 2021-02-01 09:23

With Beta 4, I had this code that worked fine:

var red, green, blue, alpha: UnsafePointer
red = UnsafePointer.alloc(1)
green = Unsa         


        
4条回答
  •  孤街浪徒
    2021-02-01 10:08

    UnsafePointer no longer has a member .alloc. Use UnsafeMutablePointer.alloc instead. e.g. the following blankof() works as a universal initializer.

    func blankof(type:T.Type) -> T {
        var ptr = UnsafeMutablePointer.alloc(sizeof(T))
        var val = ptr.memory
        ptr.destroy()
        return val
    }
    
    var red   = blankof(CGFloat)
    var green = blankof(CGFloat)
    var blue  = blankof(CGFloat)
    var alpha = blankof(CGFloat)
    color.getRed(&red, green:&green, blue:&blue, alpha:&alpha)
    CGContextSetRGBStrokeColor(context, red, green, blue, 1)
    // no need to dealloc because they are all structs, not pointers
    

提交回复
热议问题