2017-04-25 151 views
1

我很难搞清楚如何将计算结果分配给一个变量,如您所见,它是一个可选项,并且在我尝试为其赋值时保持零。为什么我不能为测量<UnitMass>变量赋值?

我最初试图做一个直接的任务。 value财产如此:

oneRepMax?.value = liftWeight * (Double(repetitions) ^^ 0.10) 

但这并没有工作。然后我决定我需要的分配过程中指定unit(基于当前用户的默认单元上),所以我想这(这里是完整的上下文):

func calculateOneRepMax() -> Measurement<UnitMass> { 

let defaultWeightUnit = UserDefaults.weightUnit().unitName <-- returns "kg" 
let unit = UnitMass(symbol: defaultWeightUnit) <-- 'po unit' shows <NSUnitMass: 0x61000003ffa0> kg 
switch withFormula {   
    case "Lombardi": 
     let result = liftWeight * (Double(repetitions) ^^ 0.10) 
     oneRepMax? = Measurement(value: result, unit: unit) 
    *case next case...* 
} 

我真的认为这会工作,但仍,oneRepMax是零。

我已阅读了Apple的文档,甚至查看了一些Ray Wenderlich屏幕录像,但还没有找出答案。预先感谢您提供的任何帮助。

回答

2

更改此:

oneRepMax? = Measurement(value: result, unit: unit) 

到:

oneRepMax = Measurement(value: result, unit: unit) 

如果oneRepMax是目前与nil值的可选值,则分配时不使用oneRepMax? = ...发生。

iOS/Swift: Can't assign optional String to UILabel text property的回答是相关的,并提供了更多的解释。

+0

就在我以为我有可选项计算出来......哦。谢谢! – Jim

相关问题