swift - 如何在函数中使用公式词典中的公式

标签 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 给我错误,比如“一行上的连续语句必须用 ';' 分隔”这告诉我我尝试使用的语法不正确。

顺便说一句,我不确定是否应该为此使用字典,但经过大量作业后,我相信这是正确的选择,因为我需要迭代它以在需要时获取值我需要知道键/值对的数量,以便我可以执行诸如在 TableView 中显示它们的名称之类的操作。

我广泛地寻找答案,一遍又一遍地阅读苹果的文档,但我真的陷入了困境。

谢谢

最佳答案

formulas["Epley"] 返回一个可选的闭包,需要 在将其应用于给定数字之前先将其展开。有多种选项可供您选择:

可选绑定(bind)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
    }
}

这可以通过可选链接来缩短 零合并运算符 ??:

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

如果不存在的 key 应被视为 fatal error 返回默认值,那么 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)
}

关于swift - 如何在函数中使用公式词典中的公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37229365/

相关文章:

delphi - 将匿名方法分配给接口(interface)变量或参数?

php - WordPress 钩子(Hook)中的匿名函数

arrays - Filter Custom Array时间优化

Swift 如何存储和检索集合类型

ios - 如何快速将灰度图像转换为二值图像?

json - 修改 Swift 字典中的所有键名

ios - 如何在闭包中访问类的变量?

swift - 不必要的水平滚动xcode

python - 如何扩展字典以包含所有匹配值?

c++ - 列出 map 变量中的项目