存储快快的数组的引用 [英] Storing a reference to array in swift

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

问题描述

我想一个数组传递给一个对象,并存储到这个数组的引用。我希望能够修改这个对象中数组并确保它的修改在其他地方。

I want to pass an array to an object and store a reference to this array. I want to be able to modify this array within this object and make sure that it's modified everywhere else.

下面就是我试图完成(如何code不工作)

Here is what I am trying to accomplish (how the code doesn't work)

class Foo {
   var foo : Array<Int>

   init(foo: Array<Int>) {
      self.foo = foo
   }

   func modify() {
      foo.append(5)
   }
}

var a = [1,2,3,4]
let bar = Foo(a)
bar.modify()
print(a) // My goal is that it will print 1,2,3,4,5

我的发现至今

A)的阵列(默认)传递奇怪的方式。这是一个参考,直到你修改数组长度。只要您修改长度将被复制和修改。作为结果,如果我追加或在对象中删除从它什么也不会被外

A) The array (by default) are passed strange way. It's a reference until you modify an array length. As soon as you modify a length it will be copied and modified. As result, if I append or delete anything from it in the object it won't be seen outside

B)我可以使用 INOUT 函数参数。这将让我在这个函数中进行修改。但是,只要我会尽量把它分配给某些对象的成员,我再次击打)

B) I can use inout on a function parameter. This will allow me to modify it within this function. However, as soon as I will try to assign it to some object member I am again struck by A)

C)我可以包装在一些容器类的数组。这可能是最彻底的方法。然而,序列化/反序列化这些对象,我宁可不把它放在容器(因为我将必须解决一些事情的序列化和反序列化,并将其发送到服务器)。

C) I can wrap an array in some Container class. This probably is the cleanest way. However, I serialize/deserialize these objects and I would rather not put it in Container (because I will have to work around some things for serialization and deserialization and sending it to the server).

是否有什么事吗?我缺少一些斯威夫特构造,让我这样做呢?

Are there anything else? Am I missing some Swift construct which allows me to do that?

推荐答案

您将不得不使用一个NSArray或NSMutableArray里为这一点,因为斯威夫特数组是值类型,所以任何分配将进行复印。

You'll have to use an NSArray or NSMutableArray for this because Swift Arrays are value types so any assignment will make a copy.

这篇关于存储快快的数组的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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