Date
May. 20th, 2024
 
2024年 4月 13日

Post: Swift struct type recursion

Swift struct type recursion

Published 12:06 Jun 11, 2018.

Created by @ezra. Categorized in #Programming, and tagged as #iOS.

Source format: Markdown

Table of Content

the 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)
}

and the classes in Swift also support recursive types:

class TreeNode<E> {
  var leftNode:TreeNode<E>
  var rightNode:TreeNode<E>
  var element:E
}

It's feels like 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
}

But you just can't do it with structs:

Value type 'TreeNode<E>' cannot have a stored property that recursively contains it.

Why can't structs have recursive value types in Swift? Is this a temporary limit of the language or is it as intended?

The answer is in the 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.

Pinned Message
HOTODOGO
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF