如何使用 [Any] 类型的参数调用 Swift Any 类型的函数
How to call Swift functions of type Any with args of type [Any]
我目前正在 Swift 中实施 this blog post about vms and compilers in Python。我 运行 遇到了一个问题:
我在 Any
中有一个函数。我在 [Any]
中有它的论据。我想在不知道它是什么参数的情况下调用这个函数。在 Python post 中,由于 Python 是动态的,所以很简单,但在 Swift 中,我认为这是不可能的。你有什么实现方法吗?
let numberOfArgs: Int = try intify(instruction.arg)
let arguments: [Any] = (0 ..< numberOfArgs).compactMap { _ in
return (stack.pop() as? Instruction)?.arg
}
let function: Any = try popVal(&stack)
function
是一个 Swift 闭包。例如 (Int, Int) -> Int
、(String, (Bool, Date) -> Date) -> Float
总之,我想用arguments
调用function
一种方法是将您的函数包装在 ([Any]) -> Any
类型的闭包中。然后在闭包中,解压参数,将它们向下转换为正确的类型并调用函数。最后,将结果转换为 Any
:
func add(a: Int, b: Int) -> Int {
return a + b
}
func mult(a: Double, b: Double) -> Double {
return a * b
}
var functions = [Any]()
var inputs = [[Any]]()
let f: ([Any]) -> Any = { arr in
return add(a: arr[0] as! Int, b: arr[1] as! Int) as Any
}
functions.append(f)
inputs.append([3, 5])
let g: ([Any]) -> Any = { arr in
return mult(a: arr[0] as! Double, b: arr[1] as! Double) as Any
}
functions.append(g)
inputs.append([6.0, 7.0])
// Each time through the loop, get one function stored as Any and
// one array of inputs with type [Any]
for (function, input) in zip(functions, inputs) {
// Downcast function from Any to ([Any]) -> Any
let f = function as! ([Any]) -> Any
// Call the function
print(f(input))
}
输出:
8
42.0
我目前正在 Swift 中实施 this blog post about vms and compilers in Python。我 运行 遇到了一个问题:
我在 Any
中有一个函数。我在 [Any]
中有它的论据。我想在不知道它是什么参数的情况下调用这个函数。在 Python post 中,由于 Python 是动态的,所以很简单,但在 Swift 中,我认为这是不可能的。你有什么实现方法吗?
let numberOfArgs: Int = try intify(instruction.arg)
let arguments: [Any] = (0 ..< numberOfArgs).compactMap { _ in
return (stack.pop() as? Instruction)?.arg
}
let function: Any = try popVal(&stack)
function
是一个 Swift 闭包。例如 (Int, Int) -> Int
、(String, (Bool, Date) -> Date) -> Float
总之,我想用arguments
function
一种方法是将您的函数包装在 ([Any]) -> Any
类型的闭包中。然后在闭包中,解压参数,将它们向下转换为正确的类型并调用函数。最后,将结果转换为 Any
:
func add(a: Int, b: Int) -> Int {
return a + b
}
func mult(a: Double, b: Double) -> Double {
return a * b
}
var functions = [Any]()
var inputs = [[Any]]()
let f: ([Any]) -> Any = { arr in
return add(a: arr[0] as! Int, b: arr[1] as! Int) as Any
}
functions.append(f)
inputs.append([3, 5])
let g: ([Any]) -> Any = { arr in
return mult(a: arr[0] as! Double, b: arr[1] as! Double) as Any
}
functions.append(g)
inputs.append([6.0, 7.0])
// Each time through the loop, get one function stored as Any and
// one array of inputs with type [Any]
for (function, input) in zip(functions, inputs) {
// Downcast function from Any to ([Any]) -> Any
let f = function as! ([Any]) -> Any
// Call the function
print(f(input))
}
输出:
8 42.0