gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:03:35 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com