ios - captureStillImageAsynchronouslyFromConnection 的函数声明和参数描述冲突?

标签 ios swift avfoundation

根据类引用,captureStillImageAsynchronouslyFromConnection 的完成处理程序接受一个 NSError 对象,但它不是可选的。

函数声明:

func captureStillImageAsynchronouslyFromConnection(connection: AVCaptureConnection!, completionHandler handler: ((CMSampleBuffer!, NSError!) -> Void)!)

然而在参数的描述中,它说如果请求被满足,完成处理程序中可能会返回 nil 来代替 NSError 对象。

参数说明:

If the request could not be completed, an NSError object that describes the problem; otherwise nil.

描述表明声明应该包含 NSError 对象的可选,不是吗?参数描述和函数声明不冲突吗?

最佳答案

只要您不解包并使用一个空的可选值,就可以了。

这是一个示例代码来显示变化。请注意,回调签名使用隐式解包选项,而传递的参数可以为 nil。

import Foundation

struct Buffer {
}

func foo(callback: (buffer: Buffer!, error: NSError!) -> Void) {
    print("#1: buffer and error are nil")
    callback(buffer: nil, error: nil)
    print("#2: buffer not nil, error is nil")
    callback(buffer: Buffer(), error: nil)
    print("#3: buffer is nil, error is not nil")
    callback(buffer: nil, error: NSError(domain: "domain", code: 123, userInfo: nil))
    print("#4: both buffer and error are not nil")
    callback(buffer: Buffer(), error: NSError(domain: "domain", code: 123, userInfo: nil))
}

func cb(buffer: Buffer!, error: NSError!) {
    if let buffer = buffer {
        print(buffer)
    }
    else {
        print("buffer is nil")
    }

    if let error = error {
        print(error)
    }
    else {
        print("error is nil")
    }
}

foo(cb)

从这个例子可以看出,一个隐式的解包可选可以是 nil。这就是 NSError 的描述。

关于ios - captureStillImageAsynchronouslyFromConnection 的函数声明和参数描述冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36124875/

相关文章:

ios - 获取 AVAudioPlayer 一次播放多种声音

json - 为什么我在Swift文件中解开nil?

ios - 当手指在该 View 内的 UIButton 上时,触摸时拖动 UIView 不起作用

ios - 将整数从 0 到 255(1 字节)转换为 NSDATA

ios - 单击“查看”后的动画

xcode - 多引号问题

ios - map 仅部分显示在 Splitview 中

ios - 捏合手势比例重置为 1?

ios - SwiftUI:如何以编程方式更改 rootview Controller

ios - 使用 AudioMixInputParameters AVFoundation 为每个视频轨道设置多个音量在 Swift iOS 中不起作用