简体   繁体   中英

Is a closure that is passed in as a parameter assigned to the parameter name in swift?

This code is from this blog.

Is the reason we can call completion() because the closure that's passed in () -> () is essentially assigned to the parameter completion and so calling completion executes the closure?

func thisNeedsToFinishBeforeWeCanDoTheNextStep(completion: () -> ()) {
    print("The quick brown fox")
    completion()
}

func thisFunctionNeedsToExecuteSecond() {
   print("jumped over the lazy dog")
}

If that's the case re: calling the function below I don't quite get how the code below translates into the first function being called and completed before the thisFunctionNeedsToExecuteSecond() is? What I mean by that is how is the ()->() in resulting in the completion() executing before thisFunctionNeedsToExecuteSecond() is called - it's hard explaining this in writing.

thisNeedsToFinishBeforeWeCanDoTheNextStep { () -> () in
    thisFunctionNeedsToExecuteSecond()
}

If you create a function with a closure as one of its input parameters, the closure is executed as soon as you call it by inputParameterName() . The parentheses after the name of the input parameter mark the function call with no input parameters to the closure, since its type in your case is Void->Void .

In your second example,

thisNeedsToFinishBeforeWeCanDoTheNextStep { () -> () in
    thisFunctionNeedsToExecuteSecond()
}

you see a trailing closure. If the last input parameter of a function is a closure, the function call can be converted to the trailing closure syntax, where you can omit the name of the closure (completion in your case) and the code between the {} will be executed once the closure is called.

So the above code is equivalent to

thisNeedsToFinishBeforeWeCanDoTheNextStep(completion: { () -> () in
    thisFunctionNeedsToExecuteSecond()
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM