【问题标题】:Why can't I assign a value to a Measurement<UnitMass> variable?为什么我不能为 Measurement<UnitMass> 变量赋值?
【发布时间】:2017-04-25 14:24:34
【问题描述】:

我很难弄清楚如何将计算结果分配给变量,fileprivate var oneRepMax: Measurement&lt;UnitMass&gt;? 正如您所看到的,它是一个可选的,并且在我尝试为其分配值后它只是保持为 nil。

我最初尝试像这样直接分配给 .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 的截屏视频,但还没有找到答案。提前感谢您提供的任何帮助。

【问题讨论】:

    标签: swift swift3 measurement


    【解决方案1】:

    改变这个:

    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 的答案是相关的,并提供了更多解释。

    【讨论】:

    • 就在我以为我已经找到了可选方案的时候......哦,好吧。谢谢!
    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 2014-05-12
    • 2022-06-11
    • 2018-11-12
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多