vanelizarov
vanelizarov

Reputation: 1073

Cannot assign value of type Int to element of Int array in Swift 2.1

In my app I have ViewController class. In this class I have instance variable queue, which is array of type Int. In one of functions, I need to assign a value of type Int to the one of the elements of this array. The app builds without any errors and warnings, runs perfectly until it throws EXC_BREAKPOINT only in that place, where I have this assignment (in function called findPath). Here's the code:

class ViewController: UIViewController {

     var queue = [Int]()

     func findPath(source: Int, target: Int) {

          queue[0] = 0 // here comes the EXC_BREAKPOINT

     }

}

It doesn't matter, which value I want to assign to this element: 0, -1, 1000 and so on, it always throws an exception.

I'm working in latest version of Xcode 7.2 7C68, latest iOS 9.2 SDK. I'm deploying to 8.1 and testing the app on my iPhone 5S with iOS 8.1.2 onboard.

Upvotes: 2

Views: 1175

Answers (1)

Dan Beaulieu
Dan Beaulieu

Reputation: 19954

var queue = [Int]()

The code above creates a new instance of an array of ints, however this instance doesn't have any values yet. In your current code you're attempting to access the first value in your queue array... since there isn't a value at your given index, you get an error.

If you're trying to add values to a new array you can do it with append:

var queue = [Int]()

func findPath(source: Int, target: Int) {
    // do this to populate a new array
    queue.append(1)   
}

If you're looking to set new values to an array that already has values you can do this:

var queue = [0, 1, 2]

func findPath(source: Int, target: Int) { 
    // do this to change values in an existing array
    queue[0] = 0 
}

Upvotes: 2

Related Questions