ilovebigmacs ilovebigmacs - 9 days ago 5
Swift Question

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

Answer

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