首先,我想说,我知道在SO中有很多文章和问题引用了indirectSwift中的关键字.
最常用的解释indirect是允许递归枚举.
indirect我想知道它是如何允许我们使用递归枚举的,而不是只知道允许我们做什么.
是因为枚举是值类型,如果它们是以递归结构构建的,那么值类型不能很好地扩展?为什么?
indirect修改值类型行为是否更像行为类型?
以下两个例子编译得很好.有什么不同?
indirect enum BinaryTree<T> {
case node(BinaryTree<T>, T, BinaryTree<T>)
case empty
}
enum BinaryTree<T> {
indirect case node(BinaryTree<T>, T, BinaryTree<T>)
case empty
}
Run Code Online (Sandbox Code Playgroud) 当引用类型的属性具有相互较强的所有权(或具有闭包)时,会发生Swift中的引用循环.
但是,是否有可能只使用值类型的参考周期?
我在游乐场尝试了这个没有成功(错误:不允许递归值类型'A').
struct A {
var otherA: A? = nil
init() {
otherA = A()
}
}
Run Code Online (Sandbox Code Playgroud) reference-counting value-type reference-type automatic-ref-counting swift
我试图在struct下面给出的帮助下制作一棵二叉树:
struct BinaryTree {
var value: Int
var left: BinaryTree
var right: BinaryTree
}
Run Code Online (Sandbox Code Playgroud)
但我收到错误error: value type 'BinaryTree' cannot have a stored property that recursively contains it。这里的结构是值类型,所以我无法在其中创建相同的结构对象。
我怎样才能实现这个目标???