Why might an assignment in Swift not happen?

In the following Swift code, for some types T:HasDefaultValues, the assignment in init(variableValue: T) does not happen and the member variable takes the value of T.defaultValue:

protocol HasDefaultValues : Equatable {
  static var defaultValue: Self {get}
  static var alternativeValue: Self {get}
}

class MyClass<T:HasDefaultValues> : NSObject, NSCoding {
  var variable: T = T.defaultValue

  init(variableValue: T) {
    self.variable = variableValue // Executed, but assignment doesn't happen!
    super.init()
  }

// ... More code follows
}

I have single-stepped the code using the debugger, and confirmed that the value of variableValue is as expected, that execution passes over the self.variable = variableValue assignment, but that the value of self.variable does not change. The code works as expected for numerous other types T:HasDefaultValues. Might this be a compiler bug?

The code for the type T:HasDefaultValues for which assignment isn't happening is quite complex, and I've not tried to reduce things to a minimal reproducible example. I'm asking here if there are good reasons for a simple assignment to fail other than a compiler bug. If there are, this would be useful in reducing things to a minimal reproducible example.

Thanks in advance.

Answers


I think some code is changing again the variable property.

Please add an observer to check this "theory".

var variable: T = T.defaultValue {
    didSet(oldValue) {
        debugPrint("variable changed from \(oldValue) to \(variable)")
    }
}

Need Your Help

call a php variable in createmarker function

javascript php google-maps-api-3

I'm parsing with php an xml file and i'm trying to put a marker in every $item.

require js load function from a modul

javascript jquery module requirejs undefined

despite i found already some answers i could not figure it out where i made the mistake in loading the module with require js, i always get the error Uncaught