简体   繁体   中英

mutating class property on swift struct

I have Swift struct that contains a mutable class like so:

struct Foo {
  var bar: BarClass?

  mutating func foobar() {
     let bar = BarClass()
     self.bar = bar
  }
}

After seeing some odd behavior I put in a statement to print the address of BarClass() on init and deinit. On the second call to foobar, I expected to see deinit on the address of the first init, like:

init X, init Y, deinit X.

Instead, I saw init X, init Y, deinit Y.

Does that just mean the contents of the newly allocated BarClass() were copied into the original? So, other than the address, the result is the same as if the new bar replaced the original, and the original was deallocated?

Or, would it be better to just call BarClass() once, and have foobar() explicitly reset its contents.

After narrowing the problem to a test case, I discovered the problem. I mistakenly created a copy of the struct thinking it was a reference. So, new BarClass was not destroying previous because previous remained referenced by original copy of the struct.

The use case was trying to add some functionality to an existing code base with minimal change.

Thanks for feedback/confirmation that I needed to study this more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM