简体   繁体   English

快速结构上的变异类属性

[英]mutating class property on swift struct

I have Swift struct that contains a mutable class like so: 我有包含如下可变类的Swift结构:

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. 看到一些奇怪的行为后,我放入一条语句,在init和deinit上打印BarClass()的地址。 On the second call to foobar, I expected to see deinit on the address of the first init, like: 在第二次调用foobar时,我希望在第一个init的地址上看到deinit,例如:

init X, init Y, deinit X. 初始化X,初始化Y,取消初始化X。

Instead, I saw init X, init Y, deinit Y. 相反,我看到了init X,init Y和deinitY。

Does that just mean the contents of the newly allocated BarClass() were copied into the original? 这是否仅意味着将新分配的BarClass()的内容复制到原始内容中? 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. 或者,最好只调用一次BarClass()并让foobar()显式重置其内容。

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. 因此,新的BarClass不会破坏先前的版本,因为先前的版本仍被该结构的原始副本引用。

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. 感谢您的反馈/确认,我需要进一步研究。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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