简体   繁体   English

如何在Swift中使用函数类型参数定义函数

[英]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.

相关问题 如何在 Swift 中定义使用 class 类型作为参数的 function? - How to define function that uses class type as a parameter in Swift? 如何在Swift中定义一个包含另一个无参数的函数的返回类型? - How to define a return type of a function which contains another, no parameter, function in Swift? Swift中的函数参数类型 - Function parameter type in Swift 如何在Swift中将类类型作为函数参数传递? - How to pass a class type as a function parameter in Swift? Swift 3 - 如何将回调函数定义为参数 - Swift 3 - How can i define callback function as parameter 如何在swift中为函数类型定义一个可选变量,它可以是nil? - How to define in swift an optional variable for a function type, which can be nil? 如何在Swift 3中调用具有相关类型参数的泛型函数 - How to call a generic function with parameter of associated type in Swift 3 如何快速将任何类型的任意数量的参数的函数用作参数 - How to take a function of any number of parameters of any type as a parameter in swift 如何在Swift中的泛型类中的函数参数中使用泛型 - How to use generic type in function parameter from generic class in Swift Swift:以枚举类型作为参数递归调用函数 - Swift : Recursively calling a function with an enum type as a parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM