user1642309
user1642309

Reputation:

Array spontaneously emptying

I'm currently working on an app, and for some reason an array is spontaneously emptying.

I first mention it at the top of the file:

let scaleTypes = [String]()

I then populate it (I verify it's populated by running a println of the array):

let scaleTypes = scaleTypesDict.valueForKey("Types")! as! [String]
println(scaleTypes.count)

When I access the array (when populating the contents of UITableViewCells):

cell.textLabel!.text = scaleTypes[indexPath.row]

I get fatal error: Array index out of range. I've done a println of the array count directly before I access the array, and found that it's emptied itself (it prints 0). The array is not mentioned elsewhere in the file. I use a similar variable name in another view controller in this app, but I highly doubt that that is causing the issue. Anyone got anything?

EDIT: If viewing the entire source code would help, it can be found here: https://gitlab.carson-greene.com/cgreene/scales-ios/tree/dev/Scale%20Randomizer. Unfortunately, I haven't commented things well; be warned. The file that this error happens in is the SRSettingsViewController.swift file.

Upvotes: 1

Views: 61

Answers (3)

Aaron Brager
Aaron Brager

Reputation: 66252

The second time you write let scaleTypes, you are declaring a new array, local to the method it's in.

Change your first let to var, and then append the values later instead of making a new array.

Also, you shouldn't use valueForKey(). Just use the keyed subscripts:

// Declare the variable as mutable
var scaleTypes = [String]()


// Later, add new variables…
if let newScales = scaleTypesDict["Types"] as? [String] {
    scaleTypes += newScales
}

Upvotes: 3

Airspeed Velocity
Airspeed Velocity

Reputation: 40965

You are declaring two different variables called scaleTypes.

The first is a member variable, which since you declare with let and then initialize to be empty, will never contain anything.

Then, in your viewDidLoad you are declaring a new, local variable called scaleTypes. You put values in it, but it only exists while your viewDidLoad function is running, where it masks the member variable. When that function exits, it disappears.

Elsewhere in other functions, when you access scaleTypes, you are accessing that empty member variable.

If instead you declare your member variable with var, and then drop the let in front of the assignment in viewDidLoad, you’ll assign the values to the member variable as you’re hoping.

Upvotes: 3

Kametrixom
Kametrixom

Reputation: 14973

Remove the let before populating the array, you're creating a local scoped array with the same name

Upvotes: 2

Related Questions