如何插入字符串的2D数组

时间:2016-07-26 13:31:42

标签: ios arrays swift string 2d

我有一个tableview,其中我想要从服务器加载多个部分,因此我需要一个2D数组。

我尝试过的是:

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)

        }
    }
}

当我运行它时,我收到了这条消息:

  

指数超出范围

我尝试用+ =插入我的元素,但它甚至不让我运行它。

我也试过这个:

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

我也遇到了同样的错误。

1 个答案:

答案 0 :(得分:1)

如评论中所述,当您尝试追加

时,数组self.i中不存在索引为self.district的数组元素
self.district[self.i].append(object["district"] as! String)

并且您必须首先将新元素附加到self.district

你也应该摆脱导致这种情况的所有强迫演员as! 程序如果失败就会崩溃。您的代码可能如下所示:

var sections = [String]()
var districts = [[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) {
                districts[idx].append(dist)
            } else {
                sections.append(town)
                districts.append([dist])
            }
        }
    }
}

或者(如现在删除的评论中所建议的),存储 自定义结构的单个数组中的信息:

struct SectionInfo {
    let town: String
    var districts: [String]
}


var sections = [SectionInfo]()
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({ $0.town == town }) {
                sections[idx].districts.append(dist)
            } else {
                sections.append(SectionInfo(town: town, districts: [dist]))
            }
        }
    }
}