swift - Method parameters in nested closure -


i trying understand how parameters passed method available nested closures. i'm nervous wrote won't have original parameters available.

(these drastically simplified examples)

i have method wrote specifies closure parameter:

func savenameandagetoserver(serverparams: [string:string], completionhandler: (age: nsnumber) -> ()) {      // connect server     // post name , dob serverparams     // receives current age in completion:      completionhandler(age: 22) } 

now somewhere else create method, specifies closure, takes 2 parameters , calls first function:

func awesomefunc(name: string, dob: nsdate, completionhandler: (isovertwentyone: bool) -> ()) {      let formatteddob = nsdateformatter().stringfromdate(dob)      savenameandagetoserver([name:formatteddob]) { (age) -> () in          if (age int) >= 21 {              print("\(name) can have beer.")             completionhandler(isovertwentyone: true)          } else {              print("\(name) young drink, can have water.")             completionhandler(isovertwentyone: false)         }     }  } 

am able guarantee parameters (name , dob) passed latter function available?

what i'm trying ask memory savenameandagetoserver closure runs within have parameters of awesomefunc available it? i'm pretty sure function being held while whatever calls completed love 2nd opinion.

you correct, captured variables last life of closure. here's exert on capturing variables apple's swift documentation:

a closure can capture constants , variables surrounding context in defined. closure can refer , modify values of constants , variables within body, if original scope defined constants , variables no longer exists.

in swift, simplest form of closure can capture values nested function, written within body of function. nested function can capture of outer function’s arguments , can capture constants , variables defined within outer function.

https://developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/closures.html


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -