这个错误是什么意思?不能下标值类型

时间:2015-12-24 10:14:09

标签: ios swift

获取错误:无法使用索引类型Int

下标值类型[String:Double]
  override func tableView(tableView: UITableView,
    cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {//1
        let cell = tableView.dequeueReusableCellWithIdentifier("cell",
            forIndexPath: indexPath) //2
        cell.textLabel?.text = menuItems.items[indexPath.section][indexPath.row]
        return cell
}

我的MenuItems如下所示:

class MenuItems:NSObject{

    var sections:[String] = []
    var items:[[String:Double]] = []

    func addSection(section: String, item:[String:Double]){
        sections = sections + [section]
        items = items + [item]
    }
}

class AnnMenuItems: MenuItems {
    override init() {
        super.init()
        addSection("Threading", item: ["Eye Brows":100,"Upper Lip":100,"Forehead":100,"Chin":100,"Sides":100,"Face Waxing/Face Threading":100])
        addSection("Hair", item: ["Rebonding":100,"Hair Dye":100,"Head Massage":100,"Streaking":100,"Hair Cut":100,"Straight Cut":100,"Children Cut":100,"Step Cut":100,"Layer Cut":100])
        addSection("Waxing", item: ["Full Arms":100,"3/4 Arms":100,"Under Arms":100,"Full Legs":100, "3/4 Legs":100,"Half Legs":100])
        addSection("Hair Treatments", item: ["Hair Spa":100,"Dandruff":100,"Hair Fall Treatment":100,"Galvanic Treatment":100, "Hair Wash":100,"Colour/Henna/Oil":100])
        addSection("Facial", item: ["Clean Up Normal":100,"Black Heads":100,"Clean Up Special":100,"Herbal Facial":100, "Fruit Facial":100])
    }
}

1 个答案:

答案 0 :(得分:2)

menuItems.items的内容属于Dictionary[String:Double],意味着其密钥为String s,而其值为Double s。

您现在正在尝试获取密钥indexPath.row的值,即Int。但关键是我们刚才说String

您不能也不应该按索引访问字典,因为它是无序数据容器。

修改

如果您正在使用部分并尝试将所有项数据存储在一个属性中,则该属性应为[[TheObjectYouStore]]类型。外部数组是部分,内部数组是行。您目前只有[TheObjectYouStore],而您实际存储的属性是字典。

您应该做的是创建一个名为Item的新类/结构,其中包含descriptionnumber,例如description="Eye Brows", number=100。然后,您可以相应地更改方法addSection的签名和items的类型:

struct Item {
    var description : String
    var number : Int
}
var items:[[Item]] = []

func addSection(section: String, item:[Item]){
    sections = sections + [section]
    items = items + [item]
}