Leonardo Marques
Leonardo Marques

Reputation: 3951

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
}

Upvotes: 17

Views: 7277

Answers (2)

Mike Pollard
Mike Pollard

Reputation: 10195

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 blog post A persistent tree using indirect enums in Swift

Upvotes: 8

FreeNickname
FreeNickname

Reputation: 7764

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.

Upvotes: 26

Related Questions