You must change the struct to class to make it work.
Because struct copied by value, so in this line
return Adjuster(target:self)
The adjuster will receive a new copy of the target and save it. In the increment method, you are trying to change self.target.value , which means that you are changing self.target , so you are essentially changing self .
But there are more problems because struct is a value type, therefore
var count: Count
count.value expected to be 1, however this is not the case. count.value will remain 0, and adjuster.target.count will be 1. Now you enter the code now very confusing, and you are wondering what happened.
The real problem is that you are introducing a design pattern from OOP with a primitive for a purely functional template, so they do not work together well.
If you are attached to a best practice guide and prefer a struct over class , you can also use a functional approach. those. no mutation
struct Count { let value = 0 } func increment(count:Count, delta:Int) -> Count { return Count(value:count.value + delta) }
source share