ilovebigmacs
ilovebigmacs

Reputation: 993

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

Upvotes: 10

Views: 3116

Answers (1)

ganzogo
ganzogo

Reputation: 2614

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

Upvotes: 8

Related Questions