swift - Implicitly unwrapped multiplication and division -


i've isolated following code in playground. in playground, noted compile time errors:

class myclass {     var weight: double!      func toounces() {         weight *= 0.035274          // 'double!' not identical 'uint8'         weight = weight * 0.035274  // works     }      func tograms() {                 weight /= 0.035274          // 'double!' not identical 'float'         weight = weight / 0.035274  // works     } } 

i following example online using nscoder, decodedoubleforkey() double? being used, hence implicitly unwrapped optional var weight: double!.

i'm debating how correct do, , fixed in code.

my question is, why these compile time errors? why multiplication compare uint8 , division compares float? there i've been missing years regarding *= , /= ?

i'm still learning this, i'm missing basic property.

you can make *= operator work explicitly unwrapping optional first so:

func toounces() {     weight! *= 0.035274 } 

you can see why looking @ how *= defined.

func *=(inout lhs: double, rhs: double) 

an implicitly unwrapped optional can't passed inout parameter because wrapper around double (or nil.)

non inout arguments can unwrapped automatically because function needs value can extracted optional automatically rather reference actual value. that's why * operator works double! defined such.

func *(lhs: double, rhs: double) -> double 

adding ! after weight in code changes passing reference optional passing reference double encased in optional. if *= had normal function syntax , remove sugar might this:

func multiplyassign (inout lhs: double, rhs: double){     lhs = rhs * lhs } var weight: implicitlyunwrappedoptional<double> = 0.0 multiplyassign(&weight, 10.0) //trying pass reference implicitlyunwrappedoptional<double> (error) multiplyassign(&(weight!), 10.0) //passing reference double 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -