Swift Recursion

Why don't Swring structures have recursive values ​​in Swift? Is this the time limit of the language or how is it intended?

I feel that the ability to declare a binary tree node as a structure with recursive types in it is the most natural implementation.

struct TreeNode<E>{ var leftNode:TreeNode<E> var rightNode:TreeNode<E> var element:E } 
+5
source share
2 answers

The answer to your question: structs are value types. If you include substructure B in struct A , it means that one object of type A will have sizeof(all_other_fields_of_A) + sizeof(B) . Thus, the type of value cannot be recursive: it will have infinite size.

+9
source

Enums in Swift support recursive types using the indirect keyword, so you can do something like:

 indirect enum Tree<T> { case Node(left: Tree?, right: Tree?, element: T) } 

Check out this great Permanent Tree blog post using Indirect Enumerations in Swift

+5
source

Source: https://habr.com/ru/post/1245303/


All Articles