0

I just updated a working Swift 2 to Swift 3 program, and I am getting the error,

Cannot convert value of type '(Data?, NSError?) -> Void' to expected argument type 'GTMSessionFetcherCompletionHandler?'

Here are the relevant details (I hope):

let fetcher = GTMSessionFetcher(urlString:url)
fetcher.authorizer = parentController.service.authorizer
fetcher.beginFetch(completionHandler: handleDownload(studentNum))
                                      ^^^^ causing the error

The function for the completionHandler:

func handleDownload(_ studentNum:Int) -> (Data?, NSError?) -> Void {
    return { (data: Data?, error: NSError?) -> Void in
        // code for function
    }
}

GTMSessionFetcherCompletionHandler is defined in an Objective-C header, as follows:

#define GTM_NULLABLE_TYPE __nullable
typedef void (^GTMSessionFetcherCompletionHandler)(NSData * GTM_NULLABLE_TYPE data,
                                               NSError * GTM_NULLABLE_TYPE error);

I have tried changing handleDownload() to the following:

func handleDownload(_ studentNum:Int) -> (GTMSessionFetcherCompletionHandler?) {
    return { (data: Data?, error: NSError?) -> Void in
       // code for function
    }
}

but that moves the error down to this function: "Cannot convert return expression of type '(Data?, NSError?) -> Void' to return type 'GTMSessionFetcherCompletionHandler?'"

I can't figure out how to keep the curried (?) data and error variables, and have it compile.

Chris Gregg
  • 2,376
  • 16
  • 30

2 Answers2

7

As per SE-0112, NSError is now bridged to Swift as the Error protocol. In fact, if you + click on the GTMSessionFetcherCompletionHandler type in Swift, you'll see exactly how it's bridged:

typealias GTMSessionFetcherCompletionHandler = (Data?, Error?) -> Void

Therefore you simply need to change your handleDownload(_:)'s signature to reflect this:

func handleDownload(_ studentNum:Int) -> (Data?, Error?) -> Void {
    return { (data: Data?, error: Error?) -> Void in
        // code for function
    }
}
Hamish
  • 78,605
  • 19
  • 187
  • 280
  • I should add -- this affected other parts of my code, too -- I had forced some code to use NSError, and it caused a runtime error. I would not have figured out the runtime error without your response. So thank you! – Chris Gregg Sep 16 '16 at 19:14
  • @ChrisGregg Happy to help :) – Hamish Sep 16 '16 at 19:27
0
  WORequestManager.shared().genericRequest(withMethod: "GET", webserviceName: walletAPI, andParameters: params, showLoading: true, success: { (responseDictionary: [AnyHashable: Any]?) in


        }, failure: { (error: Error?) in

    })
  • While this code snippet may answer the question, it doesn't provide any context to explain how or why. Consider adding a sentence or two to explain your answer. – brandonscript Oct 27 '16 at 05:39