2

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.

1 Answer 1

3

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that solved my problem. But it has to be `var array = [myClass]()´ in the first line.
Oh yea. Forgot that bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.