对象数组包含对象内的所有相同值

时间:2021-08-20 08:01:09

I'm new in Swift and I got problem using an array of objects.

我是Swift的新手,使用一组对象时遇到了问题。

class myClass {
    var test: Int?

    static func testFunc() {
        var array = [myClass] (count: 30, repeatedValue: myClass())
        for i in 0...20 {
            array[i].test = i*2
        }

        for a in 0...20 {
            println(array[a].test)
        }
    }
}

I really have no idea what could be wrong here but my result is always 40 instead of 0 to 40:

我真的不知道这里有什么不对,但我的结果总是40而不是0到40:

Optional(40)
Optional(40)
Optional(40)
etc......

Does anyone know how to solve this problem? Almost seems a bit like a bug.

有谁知道如何解决这个问题?几乎看起来有点像一个bug。

1 个解决方案

#1


The count:repeatedValue: initializer installs the exact same object in every position of the array.

count:repeatedValue:initializer在数组的每个位置安装完全相同的对象。

So when you change array[0].test to some value, you are changing the value stored in the single myClass instance that is shared at all indexes of the array. Look at index 19 and you see the same myClass objet, with the changed value.

因此,当您将array [0] .test更改为某个值时,您将更改存储在单个myClass实例中的值,该实例在数组的所有索引处共享。查看索引19,您会看到相同的myClass对象,其值已更改。

So use a loop to initialize your array:

所以使用循环来初始化你的数组:

var array = [myClass]()

for (i in 1...20)
{
  let anItem = myClass()
  anItem.test = i
   array.append(anItem)
}

#1


The count:repeatedValue: initializer installs the exact same object in every position of the array.

count:repeatedValue:initializer在数组的每个位置安装完全相同的对象。

So when you change array[0].test to some value, you are changing the value stored in the single myClass instance that is shared at all indexes of the array. Look at index 19 and you see the same myClass objet, with the changed value.

因此,当您将array [0] .test更改为某个值时,您将更改存储在单个myClass实例中的值,该实例在数组的所有索引处共享。查看索引19,您会看到相同的myClass对象,其值已更改。

So use a loop to initialize your array:

所以使用循环来初始化你的数组:

var array = [myClass]()

for (i in 1...20)
{
  let anItem = myClass()
  anItem.test = i
   array.append(anItem)
}