Search code examples
swiftswift3measurement

Why can't I assign a value to a Measurement<UnitMass> variable?


I'm having a hard time figuring out how to assign the result of a calculation a variable, fileprivate var oneRepMax: Measurement<UnitMass>? As you can see, it's an optional and it simply stays nil after I try to assign a value to it.

I originally tried to make a direct assignment to the .value property like so:

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

but that didn't work. I then determined I need to specify the unit (based on the current user default unit) during the assignment so I tried this (here's the full context):

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

I really thought that would work but still, oneRepMax is nil.

I've read through Apple's documentation and even reviewed some Ray Wenderlich screencasts but haven't figured out that answer. Thanks in advance for any help you can provide.


Solution

  • Change this:

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

    to:

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

    If oneRepMax is an optional value currently with a nil value, then the assignment doesn't happen when you use oneRepMax? = ....

    The answer to iOS/Swift: Can't assign optional String to UILabel text property is related and provides a bit more explanation.