简体   繁体   中英

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 FetchFilesCompletionBlock = ( _ files: OPFiles?, _ error: Error?) -> Void

In the function definition, I am using the optional type of FetchFilesCompletionBlock . Even though, the function is called with a completion block, in function body onCompletion becomes nil.

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

That fetchFile(_: onCompletion:) is called as follows:

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 from the above snippet, I got a compile-time error Cannot convert value of type '(OPFiles?, NSError?) -> ()' to expected argument type 'FetchFilesCompletionBlock?' . 在此处输入图片说明

The issue is that you forgot to specify the type of onCompletion . With the declaration of onCompletion you need to also specify its type that it is FetchFilesCompletionBlock .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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