I'm trying to learn swift. When I do:
var myIntArray = [Int](count: 3, repeatedValue: 0)
myIntArray[0] = 1
myIntArray[1] = 11
myIntArray[2] = 111
// prints "my array: [1, 11, 111]"
NSLog("my int array: [%d, %d, %d]", myIntArray[0], myIntArray[1], myIntArray[2])
It works as expected, but when I wrap the int in a class like this:
class Foo {
var bar = 0
}
var myWrappedIntArray = [Foo](count: 3, repeatedValue: Foo())
myWrappedIntArray[0].bar = 1
myWrappedIntArray[1].bar = 11
myWrappedIntArray[2].bar = 111
// prints "my array: [111, 111, 111]"
NSLog("my wrapped int array: [%d, %d, %d]", myWrappedIntArray[0].bar, myWrappedIntArray[1].bar, myWrappedIntArray[2].bar)
It seems to modify the entire array when trying to modify a single element. What am I doing wrong here?
repeatedValuecreates a singleFooinstance and fills the array with pointers to this instance? But how to fix that?