Why can't structs have recursive value types in Swift? Is this a temporary limit of the language or is it as intended?
I feel that the ability to declare a binary tree node as a struct with recursive types in it to be the most natural implementation.
struct TreeNode<E>{
var leftNode:TreeNode<E>
var rightNode:TreeNode<E>
var element:E
}
A recursive data type is a type that contains other values of the same type as a property for the type.
In Swift, a struct is used to store variables of different data types. For example, Suppose we want to store the name and age of a person. We can create two variables: name and age and store value. However, suppose we want to store the same information of multiple people.
The answer is in your question: structs are value types. If you include a substruct B
into a struct A
, it means, that one object of type A
will have a size sizeof(all_other_fields_of_A) + sizeof(B)
. So, a value type can not be recursive: it would have infinite size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With