If you create a struct and have a property that is of the same type, e.g:
struct Node {
var parent: Node?
init() { }
}
You get this error:
value type 'Node' cannot have a stored property that recursively contains it
There are a few ways to work around this. One is to use a "box" class:
class Box<T> {
var value: T
init(value: T) {
self.value = value
}
}
And change your Node
struct to:
struct Node {
var parent: Box<Node>?
init() { }
}
Alternatively, wrap it with an array:
struct Node {
var parent = [Node]()
init() { }
}
But when you see this error, it's also good to reflect on whether you are building your data structure correctly. in this example our struct is called Node
, naturally nodes may refer to their parent. But since structs are value types, we are always copying the parent. If we build a tree of nodes, this copying behavior is not what we want. The simpler and probably more correct answer here is to just Node
to be a class instead:
class Node {
var parent: Node?
init() { }
}
This will remove the error and more importantly, provide the correct semantics.
Your feedback is valuable: Do you want more nuggets like this? Yes or No
.
.