Swift struct type recursive value

前端 未结 4 1821
春和景丽
春和景丽 2020-12-11 17:46

Structs can\'t have recursive value types in Swift. So the follow code can\'t compile in Swift

struct A {
    let child: A
}

A value type c

4条回答
  •  旧时难觅i
    2020-12-11 18:16

    If you know a Node will only ever have one parent (if leaf), then you could use enum and indirect case like so:

    public enum Node {
        case root(value: Value)
        indirect case leaf(parent: Node, value: Value)
    }
    
    public extension Node {
        var value: Value {
            switch self {
            case .root(let value): return value
            case .leaf(_, let value): return value
            }
        }
    }
    

    If you know that your node will always have two parents, you can just adjust the enum case to accommodate that, etc etc.

提交回复
热议问题