Reputation: 941
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.
Upvotes: 0
Views: 61
Reputation: 59496
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)")
}
}
Upvotes: 2