2016-05-14 46 views
0

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

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

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 
    } 
} 

这可以用可选链接未缴合并运算??缩短:

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) 
}