【问题标题】:Type 'OSType' does not conform to protocol 'AnyObject' in Swift 2.0类型“OSType”不符合 Swift 2.0 中的协议“AnyObject”
【发布时间】:2015-09-12 22:41:33
【问题描述】:

我刚刚使用 Swift 2.0 更新到 Xcode 7 beta。 当我将项目更新到 Swift 2.0 时,我收到了这个错误:“Type 'OSType' does not conform to protocol 'AnyObject' in Swift 2.0”。我的项目在 Swift 1.2 中完美运行。这是代码出错:

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)
        }

我尝试将 kCVPixelFormatType_32BGRA 转换为 AnyObject,但没有成功。任何人都可以帮助我吗? 对不起,我的英语不好!谢谢!

【问题讨论】:

    标签: swift swift2 xcode7 avcaptureoutput


    【解决方案1】:

    这是 Swift 1.2 中的 kCVPixelFormatType_32BGRA 定义:

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

    这是它在 Swift 2.0 中的定义:

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

    实际上OSType 是一个UInt32,它不能隐式转换为NSNumber

    当您编写 let ao: AnyObject = Int(1) 时,实际上并不是将 Int 放入 AnyObject。相反,它会将你的 Int 隐式转换为 NSNumber,这是一个类,然后将其放入。

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

    所以试试这个:

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

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

    【讨论】:

    • 这确实解决了问题。但是你的回答会更有助于解释为什么这是必要的,特别是因为 OP 的代码在 Swift 1.2 中工作。
    • @MartinR 你好,我已经更新了我的答案……希望能解释的更清楚。
    • 非常感谢!我正在将一个旧应用程序重新编码为 swift (3),并且在此问题上停留的时间比我想承认的要长。
    猜你喜欢
    • 1970-01-01
    • 2014-10-23
    • 2015-01-02
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多