简体   繁体   中英

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

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. 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. like this

func iAmAFunc(() -> Void) -> Void {
    //do stuff
}

func funcThatTakesVoidAndReturnsVoid() -> Void {
    //do stuff
}

var closureThatTakesVoidAndReturnsVoid: () -> Void = { }

iAmAFunc(funcThatTakesVoidAndReturnsVoid)
iAmAFunc(closureThatTakesVoidAndReturnsVoid)

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