Sheen D
Sheen D

Reputation: 11

Swift array set value of index not working

I have a method (contents below) where queue2 is just an [Int]. I printed a lot of things to see if everything was working up to a point.

public func cool(item: Int) {
    println(item)
    println(back)
    //queue2.insert(item, atIndex: back)
    queue2[back] = item
    println(queue2.description)
    println("done")
}

The problem is this fails at runtime and I don't know why. Apple docs say you can set the value of any index in an array with this notation, but it doesn't work. If I uncomment the commented line and comment out the one below it, everything runs fine but it doesn't provide the functionality I need. What gives?

Upvotes: 0

Views: 3053

Answers (1)

matt
matt

Reputation: 535925

If queue2 is empty, this line is illegal no matter what back is:

queue2[back] = item

You cannot refer to an index that doesn't exist, and an empty array has no indexes (indices).

Upvotes: 2

Related Questions