Closed GanZhiXiong closed 1 year ago
There is no problem if you change class GanUser2
to struct GanUser2
This is an expected behavior.
When GanUser2
is a class
, it will not trigger the setter, which means UserDefaults
will not update by this instruction.
When GanUser2
is a struct
, the setter will be triggered and update the value in UserDefaults
.
If you want to use GanUser2
as a class, consider creating a new instance just like changing struct properties does.
ex.
Defaults[.ganUser2] = GanUser2(name: "b", age: "2")
@hank121314 Thank you very much for your reply. I just started using swift and I am not very familiar with swift.😃
why class not support trigger the setter?
It is in-depth swift compiler knowledge.
Defaults
use a subscription to access the UserDefaults
storage with Key
.
In swift, there are multiple subscription access strategies depending on the type of variable.
For class
, the access strategy will be DirectToAccessor
, which means it will only use a getter.
For struct
, the access strategy will be MaterializeToTemporary
, which means it will use both getter and setter.
The reply was prompt and clear. Thank you very much!
The code below
test41
update name and age is invalid, I don't know why?