引用类型内部值类型 [英] Reference type inside value type

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

问题描述

我正在研究Swift值类型,特别是结构,以更好地了解它在不同情况下的用途.我很惊讶地看到如何使用indirect枚举来建立枚举,从而引入了参考语义的薄层.

I am exploring Swift value types particularly structs to get a better understanding of it's uses in different scenario. I was amazed to see how enum can be used to build Binary Search Tree using indirect which introduces a thin layer of reference semantics.

enum BinarySearchTree<T: Comparable> {
  case empty
  case leaf(T)
  indirect case node(BinarySearchTree, T, BinarySearchTree)
}

现在要提出一个真正的问题,我正在努力寻找的是,在值类型内引用类型会发生什么.关系将如何运作?例如内存管理,对象生命周期.

Now coming to real question, what I am struggling to find is, what will happen to reference type inside a value type. How will the relationship work? like memory management, Object lifecycle.

例如

class B {
    var data: Int = 0

    deinit {
        print("deallocated!")
    }

}

struct A {
    var b = B()
}

在上述情况下,值类型保存对引用类型的引用.

In the above case, a value type holds a reference to a reference type.

  1. deinit何时会被呼叫?
  2. 每个新的类型为A的struct实例都将引用相同的类B实例还是它们将不同.
  3. 我该怎么办?或者这是代码的味道?
  4. 还有什么?
  1. When will deinit will get called?
  2. Does every new struct instance of type A will have reference to same instance of class B or will they be different.
  3. What should I need to take care of or it is a code smell?
  4. Anything else?

推荐答案

每个结构A copy 将共享与B相同的 引用.从头开始创建的每个 new 结构A将包含一个全新的B对象.

Every struct A copy will share the same reference to B. Every new struct A, created from scratch, will hold a completely new B object.

B.deint将在零

The B.deint will be called when there are zero strong references to it (e.g., your var b is one of these strong references). For instance, if only A values hold references to a given B object then those will need to got out of scope to zero all references to this object (or their boxed copies be deallocated as well, but this might be a topic for another question.)

代码设计.如果所有这些听起来都令人困惑,并且阻碍了您的应用进度(到目前为止没有任何实际的实际好处),那么您也可以考虑将B重构为一个结构.例如,甚至 Apple建议考虑使用值类型来设计您的模型层. 此博客文章也可能有助于您下定决心.

Code Design. If these all sounds too confusing and is blocking your app progress (with no real practical benefit so far), you might consider refactoring B to a struct as well. For instance, even Apple recommends considering value types to design your model layer. This blog post might also help make up your mind.

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

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