swift - Pass scope to a named function, rather than a closure -


i separate data processing of nsurlsession separate method.

when making url request, rely on enclosing scope provide me user's callback.

this works:

static func makerequest(url: string, callback: apicallback) {   let urlobject = nsurl(string: url)   var request = createrequest(urlobject!, method: "get") // internal   var session = nsurlsession.sharedsession()   var task = session.datataskwithrequest(request){       (data, response, error) -> void in      // basic parsing, error checking, then...     callback(data, nil)    }   task.resume() } 

there's rather lot of basic parsing , error checking i'd @ application level, however, want define , pass function instead of closure datataskwithrequest method:

static func makerequest(url: string, callback: apicallback) {   let urlobject = nsurl(string: url)   var request = createrequest(urlobject!, method: "get") // internal   var session = nsurlsession.sharedsession()   var task = session.datataskwithrequest(request, completionhandler: gotresponse)   task.resume() }   static private func gotresponse (nsdata: nsdata!, response: nsurlresponse!, err: nserror!) -> void {    // parsing , handling here, instead.   // oops! don't have access callback. :( } 

this leads me question, which, despite lengthy example, language features. can pass captured scope method? in javascript accomplish using function.prototype.bind, i'm not sure how in swift.

this seems example of when use curried method. declare function first parameter of apicallback. note brackets.

static private func gotresponse(callback: apicallback)(nsdata: nsdata!, response: nsurlresponse!, err: nserror!) -> void {      // use callback: normal } 

then, use this:

var task = session.datataskwithrequest(request, completionhandler: gotresponse(callback)) 

(apologies, syntax might not 100% correct since code isn’t stand alone can’t test fully)

curried functions little finicky , had bugs in 1.1 (though got fixed in 1.2), instead of using language support them, try hand-rolling if above doesn’t work, like:

static private func gotresponse(callback: apicallback) -> (nsdata: nsdata!, response: nsurlresponse!, err: nserror!) -> void {      return { data, response, error in         // put common code, capturing callback:, in here...      } } 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -