I wrote a simple library for serializing model data and later realized I was getting writes to my data when I was only reading. I was able to reduce the problem to the following playground snippet:
class Foo {
init() { name = "test" }
var name:String { didSet { print("setting name: \(self.name)") }}
}
func map(inout foo:String) {
print("writing value: \(foo)")
}
var foo:Foo = Foo()
map(&foo.name)
The result is (to me) unexpected:
writing value: test
setting name: test
I have re-read the section on inout
parameters but saw no explicit mention of copy semantics. My hunch is that the compiler is expecting the value to be overwritten and does so itself with the initial value, if no other code does so.
Does this seem expected, or a compiler bug? In my humble opinion, it is unintuitive behavior. I was not expecting an assignment, unless it originated from my code - which it did not.
To state what is hopefully obvious, the code snippet above does not need the inout param, but I had been using a common interface for reading and writing.