如何在函数中的公式字典中使用公式

时间:2016-05-14 16:50:11

标签: swift dictionary closures

我有一个公式字典(在闭包中),我现在在函数中使用什么来计算一些结果。

var formulas: [String: (Double, Double) -> Double] = [
    "Epley": {(weightLifted, repetitions) -> Double in return weightLifted * (1 + (repetitions)/30)},
    "Brzychi": {(weightLifted, repetitions) -> Double in return weightLifted * (36/(37 - repetitions)) }]

现在我正在尝试编写一个函数,它将根据名称从字典中获取正确的公式,计算结果并返回它。

func calculateOneRepMax(weightLifted: Double, repetitions: Double) -> Double {
    if let oneRepMax = formulas["Epley"] { $0, $1 } <-- Errors here because I clearly don't know how to do this part
    return oneRepMax
}

var weightlifted = 160
var repetitions = 2

let oneRepMax = Calculator.calculateOneRepMax(weightlifted, repetitions)

现在Xcode给了我一些错误,比如'一行上的连续语句必须用';'分隔这告诉我我试图使用的语法不正确。

另一方面,我不确定是否应该使用字典,但经过大量的功课后,我确信这是正确的选择,因为我需要在需要时迭代它来获取值我需要知道键/值对的数量,这样我就可以在表视图中显示它们的名称。

我一直在寻找答案,一遍又一遍地阅读Apple的文档,我真的被卡住了。

由于

1 个答案:

答案 0 :(得分:1)

formulas["Epley"]返回需要的可选闭包 在将其应用于给定数字之前解开。您可以选择以下几种选项:

可选绑定if let

func calculateOneRepMax(weightLifted: Double, repetitions: Double) -> Double {
    if let formula = formulas["Epley"]  {
        return formula(weightLifted, repetitions)
    } else {
        return 0.0 // Some appropriate default value
    }
}

这可以通过可选链接和缩短来缩短 nil-coalescing operator ??

func calculateOneRepMax(weightLifted: Double, repetitions: Double) -> Double {
    return formulas["Epley"]?(weightLifted, repetitions) ?? 0.0
}

如果应将不存在的密钥视为致命错误 返回默认值,然后guard let 合适:

func calculateOneRepMax(weightLifted: Double, repetitions: Double) -> Double {
    guard let formula = formulas["Epley"] else {
        fatalError("Formula not found in dictionary")
    }
    return formula(weightLifted, repetitions)
}