Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnsafePointer<CGAffineTransform> from CGAffineTransform

I'm trying to create a CGPath in Swift. I'm using CGPathCreateWithRect(rect, transformPointer).

How can I get an UnsafePointer<CGAffineTransform> from a CGAffineTransform? I've tried this:

    let transform : CGAffineTransform = CGAffineTransformIdentity
    let transformPointer : UnsafePointer<CGAffineTransform> = UnsafePointer(transform)

I've also tried this:

    let transform : CGAffineTransform = CGAffineTransformIdentity
    let transformPointer : UnsafePointer<CGAffineTransform> = &transform 

but Swift complains about a '&' with non-inout argument of type.... I've also tried passing &transform directly into CGPathCreateWithRect but that stops with same error.

When I pass in transform directly, Swift "Cannot convert value of type 'CGAffineTransform' to expected argument type 'UnsafePointer'".

What's going on, and how can make this work with Swift 2.1?

like image 290
Moshe Avatar asked Dec 17 '15 19:12

Moshe


2 Answers

I've also tried passing &transform directly into CGPathCreateWithRect ...

You were almost there. transform needs to be a variable in order to pass it as an inout argument with &:

var transform = CGAffineTransformIdentity
let path = CGPathCreateWithRect(CGRect(...), &transform)

For more information, see "Interacting with C APIs" in the "Using Swift with Cocoa and Objective-C" documentation.


In Swift 3 this would be

var transform = CGAffineTransform.identity
let path = CGPath(rect: rect, transform: &transform)

or, for the identity transform, just

let path = CGPath(rect: rect, transform: nil)
like image 90
Martin R Avatar answered Nov 02 '22 08:11

Martin R


@Martin R provides the best answer, but as an alternative, I like to use my unsafe mutable pointers this way, in case you need to alter the actual pointer in the future

let path = withUnsafeMutablePointer(&transform)
{
  CGPathCreateWithRect(CGRect(...), UnsafeMutablePointer($0))
}
like image 35
Knight0fDragon Avatar answered Nov 02 '22 06:11

Knight0fDragon