Swift 结构类型递归值 [英] Swift struct type recursive value

查看:59
本文介绍了Swift 结构类型递归值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结构在 Swift 中不能有递归值类型.所以下面的代码无法在 Swift 中编译

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 can not be recursive, because it would have infinite size.But I wonder why the follow code can compile?

struct A {
    let children: [A]
}

推荐答案

数组不直接保存其值.数组本质上是一个结构,它保存对包含项目的外部内存块的引用.因此所有数组都占用相同的内存量,在结构体中使用它们没有问题.

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.

演示:

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.

这篇关于Swift 结构类型递归值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆