Swift nested functions vs Closure Variables -


i want make function fetches record cloudkit, if encounters temporary network error function should retry.

func fetchrecord(withrecordid recordid: ckrecordid, returnblock: (opterror: errortype?) -> void){      func internalreturnblock(opterror opterror: errortype?){         if nsthread.ismainthread() {             returnblock(opterror: opterror)         }         else{             dispatch_async(dispatch_get_main_queue(), {                  returnblock(opterror: opterror)             })         }     }      func internalwork(){         privatedb.fetchrecordwithid(recordid) { (optrecord, opterror) in             if let error = opterror{                 // if network error retry                 internalwork()             }             else{                 internalreturnblock(opterror: nil)             }         }     }      internalwork() } 

here define such function (simplified), if fetch encounters error retries calling nested function internalwork()

my question difference between using nested functions or creating local closure variables? example, here change internalreturnblock closure variable:

func fetchrecord2(withrecordid recordid: ckrecordid, returnblock: (opterror: errortype?) -> void){      var internalreturnblock = { (opterror: nserror?) in         if nsthread.ismainthread() {             returnblock(opterror: opterror)         }         else{             dispatch_async(dispatch_get_main_queue(), {                 returnblock(opterror: opterror)             })         }     }      func internalwork(){         privatedb.fetchrecordwithid(recordid) { (optrecord, opterror) in             if let error = opterror{                 // if network error retry                 internalwork()             }             else{                 internalreturnblock(nil)             }         }     }       internalwork() } 

what differences between using nested function vs variable block? advantages or problems?

there no difference in effect. 1 declared function name, other anonymous. both functions. , function closure in swift, both closures.

an anonymous function permitted use abbreviations of form, such omission of return in one-liner returns value. none of abbreviations makes ultimate effective difference.

however, anonymous function in swift has 1 feature declared function not — capture list. can avoid retain cycles.

f {     [unowned self] in     return self.name }  

also, anonymous function defined after declaration of function takes parameter, can use terms appear in declaration:

f(param:string) {     return param } 

but if not using features, doesn't matter use. work identically.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -