引用类型内部值类型 [英] Reference type inside value type
问题描述
我正在研究Swift值类型,特别是结构,以更好地了解它在不同情况下的用途.我很惊讶地看到如何使用indirect
枚举来建立枚举,从而引入了参考语义的薄层.
I am exploring Swift value types particularly structs to get a better understanding of it's uses in different scenario. I was amazed to see how enum can be used to build Binary Search Tree using indirect
which introduces a thin layer of reference semantics.
enum BinarySearchTree<T: Comparable> {
case empty
case leaf(T)
indirect case node(BinarySearchTree, T, BinarySearchTree)
}
现在要提出一个真正的问题,我正在努力寻找的是,在值类型内引用类型会发生什么.关系将如何运作?例如内存管理,对象生命周期.
Now coming to real question, what I am struggling to find is, what will happen to reference type inside a value type. How will the relationship work? like memory management, Object lifecycle.
例如
class B {
var data: Int = 0
deinit {
print("deallocated!")
}
}
struct A {
var b = B()
}
在上述情况下,值类型保存对引用类型的引用.
In the above case, a value type holds a reference to a reference type.
-
deinit
何时会被呼叫? - 每个新的类型为
A
的struct实例都将引用相同的类B
实例还是它们将不同. - 我该怎么办?或者这是代码的味道?
- 还有什么?
- When will
deinit
will get called? - Does every new struct instance of type
A
will have reference to same instance of classB
or will they be different. - What should I need to take care of or it is a code smell?
- Anything else?
推荐答案
每个结构A
copy 将共享与B
相同的 引用.从头开始创建的每个 new 结构A
将包含一个全新的B
对象.
Every struct A
copy will share the same reference to B
. Every new struct A
, created from scratch, will hold a completely new B
object.
The B.deint
will be called when there are zero strong references to it (e.g., your var b
is one of these strong references). For instance, if only A
values hold references to a given B
object then those will need to got out of scope to zero all references to this object (or their boxed copies be deallocated as well, but this might be a topic for another question.)
代码设计.如果所有这些听起来都令人困惑,并且阻碍了您的应用进度(到目前为止没有任何实际的实际好处),那么您也可以考虑将B
重构为一个结构.例如,甚至 Apple建议考虑使用值类型来设计您的模型层. 此博客文章也可能有助于您下定决心.
Code Design. If these all sounds too confusing and is blocking your app progress (with no real practical benefit so far), you might consider refactoring B
to a struct as well. For instance, even Apple recommends considering value types to design your model layer. This blog post might also help make up your mind.
这篇关于引用类型内部值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!