在字典中存储和访问函数

时间:2018-01-31 15:03:51

标签: swift function dictionary

我想在字典中存储和访问函数。我应该提供什么类型的? Any使函数无法使用:

func updateCalculations(_ function: String) {

    let functions : [String : Any] = ["calculateFunction1": CurrentDifferenceFunctions().calculateFunction1(), 
                                      "calculateFunction2": CurrentDifferenceFunctions().calculateFunction2()]

    let funcDict = functions[function]
    guard let function = funcDict else { return }

    func beginCalculations() {
        function() //Expression of type 'Any' is unused
    }


}

编辑:这有效!

let functions : [String : () -> Void] = ["calculateFunction1": CurrentDifferenceFunctions().calculateFunction1, 
                                         "calculateFunction2": CurrentDifferenceFunctions().calculateFunction2]

2 个答案:

答案 0 :(得分:1)

class CurrentDifferenceFunctions {

    func calculateFunction() {
        print("Hello World")
    }
}

let function = CurrentDifferenceFunctions().calculateFunction
var functions: [String: () -> Void] = ["calculateFunction": function]
functions["calculateFunction"]?()

打印:

  

Hello World

答案 1 :(得分:1)

在您的示例中,您在分配到字典期间调用calculateFunction。以下是我将如何重写它:

func updateCalculations(_ function: String) {
    let cdf = CurrentDifferenceFunctions()
    // create dictionary, type is [String: ()->()] 
    // - the compiler figures that out by inference
    let functions = [
        "calculateFunction1": cdf.calculateFunction1,
        "calculateFunction2": cdf.calculateFunction2
    ]

    // get the named function from the dictionary
    guard let fun = functions[function] else {
        return
    }

    // call it
    fun()
}