Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you alloc/dealloc unsafe pointers in Swift?

Tags:

swift

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

var red, green, blue, alpha: UnsafePointer<CGFloat>
red = UnsafePointer<CGFloat>.alloc(1)
green = UnsafePointer<CGFloat>.alloc(1)
blue = UnsafePointer<CGFloat>.alloc(1)
alpha = UnsafePointer<CGFloat>.alloc(1)
myColor.getRed(red, green: green, blue: blue, alpha: alpha)

CGContextSetRGBStrokeColor(context, red.memory, green.memory, blue.memory, 1)

red.dealloc(1)
green.dealloc(1)
blue.dealloc(1)
alpha.dealloc(1)

Now with Beta5, I get the error "'UnsafePointer.Type' does not have a member named 'alloc'".

All I'm trying to do is set the stroke color of the CGContext based on a UIColor. How am I supposed to do this now? The "withUnsafePointers" function is a bit of a joke - it's giving strange errors, and it only takes a maximum of three unsafe pointers, whereas I'm trying to use four in this case.

like image 587
user1021430 Avatar asked Aug 05 '14 03:08

user1021430


2 Answers

This works, Swift is smart enough to know what to do with the & operator:

let color = UIColor.purpleColor()
var r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat = 0
color.getRed(&r, green: &g, blue: &b, alpha: &a)
CGContextSetRGBStrokeColor(c, r, g, b, a)

If you really want to do the alloc yourself, use your favorite flavor and construct the pointer like this:

let p = UnsafeMutablePointer<CGFloat>(calloc(1, UInt(sizeof(CGFloat))))
// later don't forget to free(p)
like image 106
jstn Avatar answered Sep 28 '22 15:09

jstn


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

func blankof<T>(type:T.Type) -> T {
    var ptr = UnsafeMutablePointer<T>.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
like image 23
dankogai Avatar answered Sep 28 '22 15:09

dankogai