我是 Swift 的新手,但通过遵循 Stanford iTunes U course 慢慢学习.我有一个关于在数组中存储和调用函数的问题。
我的代码(下面)似乎正确地存储了该函数,但是当我尝试调用其中一个函数时出现此错误:'(IntegerLiteralConvertible, IntegerLiteralConvertible) -> $T6' 与(字符串,操作)
。
我找到了 this answer这有助于我到达现在的位置,但现在我被困住了。
enum Op {
case binary((Double, Double) -> Double)
}
var ops = [String: Op]()
func addOperation(symbol: String, op: Op) {
ops[symbol] = op
}
addOperation("×", Op.binary(*))
addOperation("÷", Op.binary({ $1 / $0 }))
addOperation("+", Op.binary(+))
addOperation("−", Op.binary({ $1 - $0 }))
var newValue = ops["÷"](6, 3) // Produces the error
我的理解是ops["÷"]
应该是我之前存入数组的函数。我是不是调用的不对?
最佳答案
@Nate Cook 的回答是正确的,但为什么在这种情况下必须使用枚举?考虑像下面这样使用类型别名:
var ops = [String: Op]()
func addOperation(symbol: String, op:Op) {
ops[symbol] = op
}
addOperation("×", (*))
addOperation("÷", ({ $1 / $0 }))
addOperation("+", (+))
addOperation("−", ({ $1 - $0 }))
var newValue = ops["÷"]?(3,6)
// you have to put this outside of any class
public typealias Op = (Double, Double) -> Double
关于Swift 函数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28613686/