[英]Swift closure with multiple params
我試圖用兩個參數定義一個Swift閉包,但是它拋出編譯錯誤。 我究竟做錯了什么?
var processor: (CMSampleBuffer, CVPixelBuffer) throws -> Void { (sampleBuffer, outputPixelBuffer) in
....
}
編輯:缺少=
,已在注釋中正確指出。 但是現在我試圖將此閉包作為參數傳遞,並且在聲明中給出了編譯錯誤:
func process(_ processor: ((_ sampleBuffer: CMSampleBuffer, toPixelBuffer:CVPixelBuffer) throws)? = nil) {
}
因此,以下代碼似乎在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來實現其他語言。
函數類型需要使用以下語法編寫:
(
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的左側)中的“報告導航器”找到可復制的文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.