简体   繁体   中英

Array of objects contains all identical values inside the objects

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

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:

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

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

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

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.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM