Returning any type of object in a function in Swift

1.9k Views Asked by At

I want to return a function or a value that could be Int or String or another other type in Swift from a function. What is the type that can represent all of these?

Following code throws an error due to this line in autoCurry function return self.autoCurry(function, params, numArgs: argsRemaining)

class $ {


    class func curry<P, T>(function: (P...) -> T, _ parameters: (P[])) -> ((P...) -> Any?) {
        return {
            (curryParams: P...) -> Any? in
            var params:P[] = []
            return function(reinterpretCast(parameters + curryParams))
        }
    }

    class func autoCurry<P, T>(function: (P...) -> T, _ parameters: (P[]), numArgs: Int) -> ((P...) -> Any?) {
        let funcParams: P[] = []
        let funcRef = { (curryParams: P...) -> Any? in
            if curryParams.count < numArgs {
                let argsRemaining = numArgs - curryParams.count
                let params = parameters + curryParams
                return self.autoCurry(function, params, numArgs: argsRemaining)
            } else {
                return function(reinterpretCast(curryParams))
            }
        }
        return funcRef
    }
}
1

There are 1 best solutions below

1
On

There isn't a Swift type that covers functions. The two 'generic' types explicitly exclude functions.

“Swift provides two special type aliases for working with non-specific types:

  AnyObject can represent an instance of any class type.
  Any can represent an instance of any type at all, apart from function types.”


Excerpt From: Apple Inc. “The Swift Programming Language.”
  iBooks. https://itun.es/us/jEUH0.l

thus you can't specify a return type that can cover both functions and any other type.

Side Note: It doesn't appear that your are actually performing a 'Curry' operation but rather a 'Partial Function Application'. Currying is built into Swift.