简体   繁体   English

是否将作为参数传递的闭包迅速分配给参数名称?

[英]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? 是我们之所以可以调用completion()原因,是因为() -> ()传递的闭包实际上已分配给参数完成,因此调用完成将执行闭包?

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? 如果是这样的话,请重新调用下面的函数:我不太了解下面的代码如何转换为thisFunctionNeedsToExecuteSecond()之前被调用并完成的第一个函数? 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. 我的意思是如何为()->()在导致completion()之前执行thisFunctionNeedsToExecuteSecond()被调用-这是很难以书面形式解释这一点。

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() . 如果创建的函数以闭包作为其输入参数之一,则在通过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 . 输入参数名称后面的括号标记函数调用,而闭包没有输入参数,因为在您的情况下其类型为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()
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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