Reputation: 1683
This is basically what I am trying to do:
a function that can accept any function with any number of parameters and any return type
Is that even possible?
func fun1(x: Int,y: String){
}
func fun2(c: Float){
}
func thefunction(function,parameters) {
function(parameters[0],parameters[1]...)
}
thefunction(fun1,3,"hi")
thefunction(fun2,4.5)
Upvotes: 1
Views: 567
Reputation: 76
Swift does not have an apply
function. But you can use generic functions:
func fun1(x: Int, y: String){
print(x, y)
}
func fun2(c: Float){
print(c)
}
func apply<Arg1, Return>(function: (Arg1) -> Return,_ arg: Arg1) -> Return {
return function(arg)
}
func apply<Arg1, Arg2, Return>(function: (Arg1, Arg2) -> Return, _ arg1: Arg1, _ arg2: Arg2) -> Return {
return function(arg1, arg2)
}
apply(fun1, 1, "foo")
apply(fun2, 3.1)
The downside is that you need a generic apply
for each arity.
The upside is that you get a compiler error if you call a function with the wrong parameters.
Upvotes: 1
Reputation: 3015
Swift has the following type for allowing an argument of any type:
AnyObject
Additionally, you can create one parameter at the end of your parameter list which allows for a dynamic amount of arguments to be passed. I pulled this directly from the Apple documentation for reference:
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
You can see the entry here. It's amazing what a little bit of research will do..
That said, I don't actually suggest doing this. It makes your code very difficult to understand for other people. If you need to make the function so general that it can literally take any object and return any object in any amount, there is probably a better way to do it.
Upvotes: 1