我想从函数中返回一个函数或值,该函数或值可以是Int或String或Swift中的其他类型。什么类型可以代表所有这些?
以下代码因autoCurry函数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
}
}
答案 0 :(得分:3)
没有涵盖功能的Swift类型。两个“通用”类型明确排除了函数。
“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
因此您无法指定可以涵盖函数和任何其他类型的返回类型。
旁注:看起来你实际上并没有执行'Curry'操作,而是'部分功能应用'。 Curift内置于Swift中。