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.
For e.g.
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.
- 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?