Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass any function as a parameter and execute it in Swift?

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)?

like image 904
ilovebigmacs Avatar asked Nov 29 '16 15:11

ilovebigmacs


People also ask

Can you pass a function as a parameter in Swift?

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.

How do you pass a function as a parameter?

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.

Can we pass function as parameter?

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.

How do you call a function in Swift?

Calling a function in Swift In the above example, we have declared a function named greet() . func greet() { print("Hello World!") }


1 Answers

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"))
like image 121
ganzogo Avatar answered Sep 18 '22 19:09

ganzogo