Reference cycles with value types?

后端 未结 6 1413
太阳男子
太阳男子 2020-12-03 08:34

Reference cycles in Swift occur when properties of reference types have strong ownership of each other (or with closures).

Is there, however, a possibility of havin

6条回答
  •  感动是毒
    2020-12-03 08:46

    As the compiler told you, what you're trying to do is illegal. Exactly because this is a value type, there's no coherent, efficient way to implement what you're describing. If a type needs to refer to itself (e.g., it has a property that is of the same type as itself), use a class, not a struct.

    Alternatively, you can use an enum, but only in a special, limited way: an enum case's associated value can be an instance of that enum, provided the case (or the entire enum) is marked indirect:

    enum Node {
        case None(Int)
        indirect case left(Int, Node)
        indirect case right(Int, Node)
        indirect case both(Int, Node, Node)
    }
    

提交回复
热议问题