2

I am writing a function in Swift that creates a vImage_CGImageFormat from a CGImage as follows:

vImage_CGImageFormat(
    bitsPerComponent: UInt32(CGImageGetBitsPerComponent(image)), 
    bitsPerPixel: UInt32(CGImageGetBitsPerPixel(image)), 
    colorSpace: CGImageGetColorSpace(image), 
    bitmapInfo: CGImageGetBitmapInfo(image), 
    version: UInt32(0), 
    decode: CGImageGetDecode(image), 
    renderingIntent: CGImageGetRenderingIntent(image))

This doesn't compile however. That's because CGImageGetColorSpace(image) returns CGColorSpace! and the above constructor only takes Unmanaged<CGColorSpace> for the colorSpace parameter.

Is there another way to do this? Perhaps converting CGColorSpace into Unmanaged<CGColorSpace>?

fyell
  • 221
  • 1
  • 7

1 Answers1

5

This should work:

vImage_CGImageFormat(
    // ...
    colorSpace: Unmanaged.passUnretained(CGImageGetColorSpace(image)),
    //...
)

From the struct Unmanaged<T> API documentation:

/// Create an unmanaged reference without performing an unbalanced
/// retain.
///
/// This is useful when passing a reference to an API which Swift
/// does not know the ownership rules for, but you know that the
/// API expects you to pass the object at +0.
///
/// ::
///
///   CFArraySetValueAtIndex(.passUnretained(array), i,
///                          .passUnretained(object))
static func passUnretained(value: T) -> Unmanaged<T>

Update for Swift 3:

vImage_CGImageFormat(
    // ...
    colorSpace: Unmanaged.passUnretained(image.colorSpace!),
    //...
)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382