简体   繁体   English

在Swift 3中,Completion Block变为零

[英]Completion Block becomes nil in Swift 3

I checked the similar question , but the issue occurs in my case is totally different. 我检查了类似的问题 ,但是在我的情况下发生的问题完全不同。

I am using typealias to avoid rewriting similar completion block declaration. 我正在使用typealias来避免重写类似的完成块声明。

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

In the function definition, I am using the optional type of FetchFilesCompletionBlock . 在函数定义中,我使用的是FetchFilesCompletionBlock的可选类型。 Even though, the function is called with a completion block, in function body onCompletion becomes nil. 即使使用完成块调用该函数,在函数体中的onCompletion也变为nil。

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

That fetchFile(_: onCompletion:) is called as follows: 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)

If I remove the as? FetchFilesCompletionBlock 如果我删除as? FetchFilesCompletionBlock as? FetchFilesCompletionBlock from the above snippet, I got a compile-time error Cannot convert value of type '(OPFiles?, NSError?) -> ()' to expected argument type 'FetchFilesCompletionBlock?' 从上面的代码片段中获取了as? FetchFilesCompletionBlock ,我遇到了编译时错误Cannot convert value of type '(OPFiles?, NSError?) -> ()' to expected argument type 'FetchFilesCompletionBlock?' . 在此处输入图片说明

The issue is that you forgot to specify the type of onCompletion . 问题是您忘记指定onCompletion的类型。 With the declaration of onCompletion you need to also specify its type that it is FetchFilesCompletionBlock . 使用onCompletion的声明,您还需要指定其类型为FetchFilesCompletionBlock

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

问题是,在块定义中,您使用Error作为错误的类,但是在创建的块中,您使用NSError,尽管它们符合标准,但并未“隐式”强制转换,并且通过执行Nirav建议您“明确”强制转换差异(NSError到Error)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM