Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift struct type recursion

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
}
like image 326
Leonardo Marques Avatar asked Mar 18 '16 09:03

Leonardo Marques


People also ask

What is recursive type in Swift?

A recursive data type is a type that contains other values of the same type as a property for the type.

What is struct in Swift UI?

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.


1 Answers

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.

like image 125
FreeNickname Avatar answered Nov 04 '22 21:11

FreeNickname