0

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 from the above snippet, I got a compile-time error Cannot convert value of type '(OPFiles?, NSError?) -> ()' to expected argument type 'FetchFilesCompletionBlock?'. enter image description here

Milan Kamilya
  • 2,188
  • 1
  • 31
  • 44

2 Answers2

1

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)
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • Thanks @Nirav , it works well. Could you please tell the reason behind? – Milan Kamilya Jun 21 '17 at 09:12
  • 1
    @MilanKamilya Welcome mate :), I have already written that you haven't specify the type of `onCompletion` with its declaration that's the issue. – Nirav D Jun 21 '17 at 09:13
  • Could you please tell what is the difference between `as? FetchFilesCompletionBlock` & `let onCompletion: FetchFilesCompletionBlock` – Milan Kamilya Jun 21 '17 at 09:21
  • @MilanKamilya Type casting with block will never going to work, so `as? FetchFilesCompletionBlock` will always fail – Nirav D Jun 21 '17 at 09:22
1

issue is that in the block definition you used Error as your error's class , but in the the block you created you used NSError instead, while they r compliant they r not "implicitly" casted, and by doing what Nirav proposed you "explicitly" casted the difference (NSError to Error)

Hussein Dimessi
  • 377
  • 3
  • 8