Swift 函数数组

标签 swift

我是 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/

相关文章:

json - 解码嵌套对象swift4 Codable

javascript - 使用 JSContext 在 swift 中调用匿名 javascript 函数

Swift “UDP Read” 代码 - unsaferawbufferpointer 编译错误

php - 如何转换 Swift 日期和 TimeInterval 以便我可以发送到 php 服务器?

swift - 将 NSNumber 转换为字符串 Swift 2

swift - 无法推断通用参数 'FalseContent'

swift - 使用 NSUserDefaults 时出错

swift - 对查询字符串非常困惑

ios - 如何从另一个类执行一个类的 collectionView 方法?

iOS Swift AVAudioPlayer 播放完毕后如何将 currentTime 重置为零