Explain Swift Closure syntax -


i new swift , closures , after regarding going on.

example 1:

func getdata(completionhandler: ((nsarray?, nserror?) -> void)?) -> void { 

so function getdata, has completion handler, of nsarray + nserror optional parameters passed function? following bit -> void)? return type void, i.e nothing set returned , whole closure optional?

i wasn't sure following -> void meant in case?

example 2:

let task = session.datataskwithurl(url!, completionhandler: {data, response, error -> void in ... } 

in case completionhandler data, response , error assigned within block constant task. correct? unsure -> void in in relation error particularly additional in?

i have spent while looking around @ various pieces of code , writing myself used syntax, pretty easy confused i'm finding out http://fuckingclosuresyntax.com/

you correct method signature. -> void)? means passing in completion handler begin optional. it's worth nothing void indicating block should not return value caller use. completion handler type there closure (anonymous function) type takes 2 arguments: 1 of optional nsarray type , 1 of optional nserror type (so either/both of might nil). returns nothing caller.

in second example, creating completion handler pass datataskwithurl method, data, response, error parameters (more on syntax in bit). -> void same before, indication block returns nothing, despite being next error. in used delimiter compiler separate closure's arguments body. syntax shorthanded little bit. use parentheses around block arguments, suppose that's personal style/taste/whatever. completionhandler definition like:

{ (data: nsdata!, response: nsurlresponse!, error: nserror!) -> void in // code, end } 

now becomes bit more clear what's going on. swift lot of inference , allows write nice , compactly can hide meaning if you're unfamiliar code. defining closure accepts 3 implicitly unwrapped optionals parameters: 1 of nsdata! type, 1 of nsurlresponse!, , 1 of nserror!. returns nothing (-> void). body of closure, i.e., whatever stuff want do, goes after in until next }. because method defines types going passed block, in implementation, parameters can infer types leaving off type annotation, going data: nsdata! data. in swift, valid leave out parentheses around closure arguments, leaving original line of code.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -