我试图定义一个带有两个参数的Swift闭包,但它抛出了编译错误。我做错了什么?
var processor: (CMSampleBuffer, CVPixelBuffer) throws -> Void { (sampleBuffer, outputPixelBuffer) in
....
}编辑:注释中正确指出的=缺失。但现在我试图将这个闭包作为一个参数传递,它在声明中给出了编译错误:
func process(_ processor: ((_ sampleBuffer: CMSampleBuffer, toPixelBuffer:CVPixelBuffer) throws)? = nil) {
}发布于 2018-09-23 02:20:46
因此,下面的代码看起来像是传入了一个游乐场:
func process(_ processor: ((String, String))? = nil) {
}我很确定主要的问题是你想强制throws作为关键字。我认为这是不可能的,我宁愿使用Result enum模式,它看起来或多或少如下所示:
enum ProcessResult {
case success(someReturnValue: YourType) // Or no associated value if you just want to know it worked
case failed(anError: Error)
}通过要求块返回一个ProcessResult,您可以强制执行在其他语言中可能使用的try/catch。
发布于 2018-09-23 06:47:21
Function Type需要使用以下语法编写:
( ArgumentList ) throws -> ResultType
(简化后,您可以在上面的链接中找到完整的描述。)
根据您的需求,关键字throws是可选的,但即使ResultType为Void,-> ResultType也是必需的。
并且ArgumentList不能有参数标签,当您想要显示参数名称以提高可读性时,需要使用_作为参数标签。
所以,你的process(_:)应该是这样的:
func process(_ processor: ((_ sampleBuffer: CMSampleBuffer, _ toPixelBuffer: CVPixelBuffer) throws -> Void)? = nil) {
//...
}或者,如果您为参数类型定义了类型别名,则可以按如下方式重写它:
typealias ProcessorType = (_ sampleBuffer: CMSampleBuffer, _ toPixelBuffer: CVPixelBuffer) throws -> Void
func process(_ processor: ProcessorType? = nil) {
//...
}另外,当您询问有关编译错误的问题时,强烈建议您显示整个错误消息。
您可以通过导航器窗格(在Xcode的左侧)中的报告导航器找到可复制的文本。
https://stackoverflow.com/questions/52459320
复制相似问题