mike vorisis mike vorisis - 4 months ago 11
Swift Question

How can I insert To an 2D array of Strings a String

I have a tableview in which I want to have multiple sections that I load from my server so I need a 2D array.

What I've tried is this:

var sections = [String]()
var district = [[String]]()
if let objects = objects {
for object in objects {
let town = object["town"] as! String
if !self.sections.contains(town){
self.sections.append(town)
self.district[self.i].append(object["district"] as! String)
self.i += 1

}else{

let f = self.sections.indexOf(town)
self.district[f!].append(object["district"] as! String)

}
}
}


When I run it I got this message:


Index out of range


I tried to insert my elements with += but it doesn't even let me run it.

I also tried this:

self.district[0][0] = object["district"] as! String


And I got the same error.

Answer

As mentioned in the comments, the array element with index self.i does not exist in the array self.district when you try to append at

self.district[self.i].append(object["district"] as! String)

and you have to append a new element to self.district first.

You should also get rid of all the forced casts as! which cause the program to crash if they fail. You code could then look like this:

var sections = [String]()
var district = [[String]]()
if let objects = objects {
    for object in objects {
        if let town = object["town"] as? String,
            let dist = object["district"] as? String {

            if let idx = sections.indexOf(town) {
                district[idx].append(dist)
            } else {
                sections.append(town)
                district.append([dist])
            }
        }
    }
}