Swift struct type recursive value

前端 未结 4 1816
春和景丽
春和景丽 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条回答
  •  温柔的废话
    2020-12-11 18:20

    The array doesn't hold its values directly. An array is essentially a struct that holds the reference to an external chunk of memory which contains the items. Therefore all arrays occupy the same amount of memory and there is no problem to use them in structs.

    To demonstrate:

    struct Value {
        var array: [Int] = [] 
    }
    
    var value = Value()
    value.array = [0, 1, 2, 3]  // this won't increase the size of the struct!
    

    If arrays behaved differently, you wouldn't be able to change their size dynamically (e.g. append elements) or to use their copy-on-write behavior. In essence, arrays & dictionaries are classes wrapped into value types.

    Therefore, your code can compile because it's not really recursive.

提交回复
热议问题