[英]How to define a function with a function type parameter in Swift
I could define a function like this 我可以定义一个这样的功能
func doWithAction(action: ()-> void) {
// something
}
However, when I use the function, the auto-completion of Xcode give me a block/closure 但是,当我使用该功能时,Xcode的自动完成功能使我无法使用
self.addPullToRefreshControllerWithAction { () -> void in
}
I know closure and function are something same in Swift, but I want to lead the one who use this function to pass a function in, not a block. 我知道闭包和函数在Swift中是相同的,但是我想带领使用此函数的人传入一个函数,而不是一个块。 The reason why I do this is I want this function to behave like a selector and a delegation
我这样做的原因是我希望此函数的行为类似于选择器和委托
yes, closure and functions are practically the same in swift, so if the function expects a closure, you can pass a function with the same signature as a parameter instead. 是的,闭包和函数实际上在swift上是相同的,因此,如果函数期望闭包,则可以传递具有与参数相同签名的函数。 like this
像这样
func iAmAFunc(() -> Void) -> Void {
//do stuff
}
func funcThatTakesVoidAndReturnsVoid() -> Void {
//do stuff
}
var closureThatTakesVoidAndReturnsVoid: () -> Void = { }
iAmAFunc(funcThatTakesVoidAndReturnsVoid)
iAmAFunc(closureThatTakesVoidAndReturnsVoid)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.