How to create CVPixelBuffer attributes dictionary in Swift

1.3k views Asked by At

To create a CVPixelBuffer attributes in Objective-C I would do something like so:

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
                         [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
                         nil];

And then in the CVPixelBufferCreate meathod I would pass (__bridge CFDictionaryRef) attributes as the parameter.

In Swift I'm attempting to create my dictionary like this:

let attributes:[CFString : NSNumber] = [
        kCVPixelBufferCGImageCompatibilityKey : NSNumber(bool: true),
        kCVPixelBufferCGBitmapContextCompatibilityKey : NSNumber(bool: true)
    ]

but I'm discovering that CFString is not Hashable and well, I have been unable to get this to work.

Can someone provide an example of how this works in Swift?

1

There are 1 answers

0
matt On BEST ANSWER

Just use NSString instead:

let attributes:[NSString : NSNumber] = // ... the rest is the same

That, after all, is what you were really doing in the Objective-C code; it's just that Objective-C was bridge-casting for you. A CFString cannot be the key in an Objective-C dictionary any more than in a Swift dictionary.

Another (perhaps Swiftier) way is to write this:

let attributes : [NSObject:AnyObject] = [
    kCVPixelBufferCGImageCompatibilityKey : true,
    kCVPixelBufferCGBitmapContextCompatibilityKey : true
]

Note that by doing that, we don't have to wrap true in an NSNumber either; that will be taken care of for us by Swift's bridging automatically.