swiftswift2xcode7avcaptureoutput

Type 'OSType' does not conform to protocol 'AnyObject' in Swift 2.0


I just updated to Xcode 7 beta with Swift 2.0. And when I updated my project to Swift 2.0, I got this error: "Type 'OSType' does not conform to protocol 'AnyObject' in Swift 2.0". My project works perfectly in Swift 1.2. And here is the code got error:

videoDataOutput = AVCaptureVideoDataOutput()
        // create a queue to run the capture on
        var captureQueue=dispatch_queue_create("catpureQueue", nil);
        videoDataOutput?.setSampleBufferDelegate(self, queue: captureQueue)

        // configure the pixel format            
        **videoDataOutput?.videoSettings = [kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_32BGRA]** // ERROR here!

        if captureSession!.canAddOutput(videoDataOutput) {
            captureSession!.addOutput(videoDataOutput)
        }

I tried to convert kCVPixelFormatType_32BGRA to AnyObject but it didn't work. Anyone could help me? Sorry for my bad English! Thankyou!


Solution

  • This is the kCVPixelFormatType_32BGRA definition in Swift 1.2:

    var kCVPixelFormatType_32BGRA: Int { get } /* 32 bit BGRA */
    

    This is its definition in Swift 2.0:

    var kCVPixelFormatType_32BGRA: OSType { get } /* 32 bit BGRA */
    

    Actually the OSType is a UInt32 which can't implicit convert to a NSNumber:

    When you write let ao: AnyObject = Int(1), it isn’t really putting an Int into an AnyObject. Instead, it’s implicitly converting your Int into an NSNumber, which is a class, and then putting that in.

    https://stackoverflow.com/a/28920350/907422

    So try this:

    videoDataOutput?.videoSettings = [kCVPixelBufferPixelFormatTypeKey: Int(kCVPixelFormatType_32BGRA)]
    

    or

    videoDataOutput?.videoSettings = [kCVPixelBufferPixelFormatTypeKey: NSNumber(unsignedInt: kCVPixelFormatType_32BGRA)