具有值类型的参考周期? [英] Reference cycles with value types?

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

问题描述

Swift中的引用周期发生在引用类型的属性相互之间具有强烈所有权(或带有闭包)时.

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 having reference cycles with value types only?

我在操场上成功尝试了此操作(错误:不允许递归值类型'A').

I tried this in playground without succes (Error: Recursive value type 'A' is not allowed).

struct A {
  var otherA: A? = nil
  init() {
    otherA = A()
  }
}

推荐答案

参考周期(或保留周期)之所以如此命名是因为它表示周期 rel ="noreferrer">对象图:

A reference cycle (or retain cycle) is so named because it indicates a cycle in the object graph:

每个箭头表示一个对象保留另一个(有力的参考).除非循环中断,否则将永远不会释放这些对象的内存.

Each arrow indicates one object retaining another (a strong reference). Unless the cycle is broken, the memory for these objects will never be freed.

在捕获和存储值类型(结构和枚举)时,没有引用作为参考.值可以复制,而不是被引用,尽管值可以保存对对象的引用.

When capturing and storing value types (structs and enums), there is no such thing as a reference. Values are copied, rather than referenced, although values can hold references to objects.

换句话说,值在对象图中可以有外向箭头,但没有外向箭头.那意味着他们不能参加一个周期.

In other words, values can have outgoing arrows in the object graph, but no incoming arrows. That means they can't participate in a cycle.

这篇关于具有值类型的参考周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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