我试图用两个参数定义一个Swift闭包,但是它抛出编译错误。我在做什么错了?
var processor: (CMSampleBuffer, CVPixelBuffer) throws -> Void { (sampleBuffer, outputPixelBuffer) in
....
}
编辑:缺少=,已在注释中正确指出。但是现在,我试图将此闭包作为参数传递,并且在声明中给出了编译错误:
func process(_ processor: ((_ sampleBuffer: CMSampleBuffer, toPixelBuffer:CVPixelBuffer) throws)? = nil) {
}
答案 0 :(得分:0)
因此,以下代码似乎在Playground中传递:
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的功能。
答案 1 :(得分:0)
Function Type needs to be written in this syntax:
(
ArgumentList )
throws
->
ResultType
(Simplified, you can find a full description in the link above.)
The keyword throws
is optional according to your requirement, but ->
ResultType is required even if the ResultType is Void
.
And ArgumentList cannot have parameter labels, you need to use _
as parameter label when you want to show parameter names for readability.
So, your process(_:)
should be something like this:
func process(_ processor: ((_ sampleBuffer: CMSampleBuffer, _ toPixelBuffer: CVPixelBuffer) throws -> Void)? = nil) {
//...
}
Or else, if you define a typealias for the parameter type, you can rewrite it as follows:
typealias ProcessorType = (_ sampleBuffer: CMSampleBuffer, _ toPixelBuffer: CVPixelBuffer) throws -> Void
func process(_ processor: ProcessorType? = nil) {
//...
}
One more, when you ask something about compilation errors, it is strongly recommended to show whole error message.
You can find a copyable text through the Report Navigator in the Navigator pane (in the Left side of Xcode).