Swift 3中的完成块变为零

时间:2017-06-21 08:52:37

标签: ios swift3 completionhandler

我检查了similar question,但问题出现在我的情况下是完全不同的。

我使用typealias来避免重写类似的完成块声明。

typealias FetchFilesCompletionBlock = ( _ files: OPFiles?, _ error: Error?) -> Void

在函数定义中,我使用的是FetchFilesCompletionBlock的可选类型。即使用完成块调用该函数,函数体中的onCompletion也变为nil。

func fetchFile(_ param: [String: String]? = nil, onCompletion: FetchFilesCompletionBlock?) {
  // I found onCompletion is nil here.
  // function body
}

调用fetchFile(_: onCompletion:)如下:

let onCompletion =  {(files, error) in
  DispatchQueue.main.async(execute: {[weak self]() in
    self?.onCompletion(files, error: error)
  })
} as? FetchFilesCompletionBlock
// Here also I found that onCompletion is nil
dataManager.fetchFile(param, onCompletion: onCompletion)

如果我从上面的代码段中删除as? FetchFilesCompletionBlock,则会收到编译时错误Cannot convert value of type '(OPFiles?, NSError?) -> ()' to expected argument type 'FetchFilesCompletionBlock?'enter image description here

2 个答案:

答案 0 :(得分:1)

问题是您忘记指定onCompletion的类型。声明onCompletion后,您还需要指定其类型为FetchFilesCompletionBlock

let onCompletion: FetchFilesCompletionBlock = {(file, error) in
    //Your code
}
dataManager.fetchFile(param, onCompletion: onCompletion)

答案 1 :(得分:1)

问题是在块定义中你使用Error作为你的错误的类,但是在你创建的块中你使用了NSError,而它们符合它们并不是“隐式”铸造的,而是通过做Nirav提出的你“明确地“改变了差异(NSError为错误)

相关问题