I'm trying to write a function that can take any function as a parameter and execute it in Swift. I have tried this approach:
public func anyFunc<P, T> (_ function: (P...) -> T) {
_ = function()
}
and then trying it with:
anyFunc(print("hello"))
This produces ERROR: 'print' produces '()', not the expected contextual result type '(_...) -> _'
How can I achieve this (and is it feasible)?
Every function in Swift has a type, consisting of the function's parameter types and return type. You can use this type like any other type in Swift, which makes it easy to pass functions as parameters to other functions, and to return functions from functions.
Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.
Calling a function in Swift In the above example, we have declared a function named greet() . func greet() { print("Hello World!") }
How about just using @autoclosure
, like so:
func anyFunc<T>(_ closure: @autoclosure () -> T) {
let result: T = closure()
// TODO: Do something with result?
}
anyFunc(print("hello"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With