Home > Back-end >  In Swift is it possible to write a function that receives another function and its parameters to lat
In Swift is it possible to write a function that receives another function and its parameters to lat

Time:07-12

Let’s say I have this function

func executeFunction<Value>(_ function: (Any...) -> Value, params: Any...) -> Value {
    //some pre processing before the function is executed
    return function(params)
}

And I want it to be able to receive any type of function with any number of parameters with just the condition of it to return something. Like, ie:

func greetUser(_ user: String) -> String {
    return "Hello \(user)"
}

executeFunction(greetUser, params: "John Doe")

Is there a way to achieve this?

CodePudding user response:

Nevermind! I found how. Turns out I needed to specify the arguments of the function and the type of the argument params as T.

func executeFunction<Value, T>(_ function: (T) -> Value, params: T = () as! T) -> Value {
    //some pre processing before the function is executed
    return function(params)
}

This way I was able to invoke the executeFunction with three different functions each having different number of parameters.

func greetUser(_ user: String) -> String {
    return "Hello \(user)"
}

func add(_ num1: Int, to num2: Int) -> Int {
    return num1   num2
}

let string = executeFunction(greetUser, params: "John Doe") // -> "Hello John Doe"
let result = executeFunction(add, params: (1,2))            // -> 3
let hello = executeFunction(sayHello)                       // -> "Hello"
  • Related