How do you alloc/dealloc unsafe pointers in Swift?

后端 未结 4 1590
我寻月下人不归
我寻月下人不归 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 09:42

    To answer your question about setting the stroke color from a UIColor, this will work:

    CGContextSetStrokeColorWithColor(myUIColor.CGColor);
    

    I do this a lot in my C++-based Quartz 2D code.

    0 讨论(0)
  • 2021-02-01 09:52

    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)
    
    0 讨论(0)
  • 2021-02-01 10:04

    As of Beta 5 you can just pass your variables prefixed with &. Just make sure to initialise them

    More info on https://developer.apple.com/swift/blog/?id=6

    To use single variables, you can just set them to a zero value

    var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
    color.getRed(&r, green: &g, blue: &b, alpha: &a)
    

    To use C arrays, you just create a normal array with the indices you expect

    var points:[NSPoint] = [NSPoint(), NSPoint(), NSPoint()] //notice how we set empty NSPoints
    self.elementAtIndex(index, associatedPoints: &points)
    CGPathAddCurveToPoint(path, nil, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y)
    
    0 讨论(0)
  • 2021-02-01 10:08

    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
    
    0 讨论(0)
提交回复
热议问题