【问题标题】:What does this error mean? cannot subscript value type这个错误是什么意思?不能下标值类型
【发布时间】:2015-12-24 10:14:08
【问题描述】:

出现错误:无法使用索引类型 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])
    }
}

【问题讨论】:

  • 我认为menuItems.items 是字典..你不能把字典索引
  • 是的。那我该怎么做呢?
  • @iosmadness 有很多方法可以做到这一点,但所有这些都需要更改 menuItems 类型。
  • text 应该是什么? ThreadingEye Brows100?
  • Threading 是标题项; Eye Brows 的子部分,价格为 100。我想把它放在一个静态表格单元格上。 text 应该是 Eye Brows : 100

标签: ios swift


【解决方案1】:

menuItems.items 的内容是Dictionarys,类型为[String:Double],这意味着它的键是Strings,而它的值是Doubles。

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

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

编辑

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

因此,您应该做的是创建一个名为Item 的新类/结构,它有一个description 和一个number,例如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]
}

【讨论】:

  • @iosmadness 我提供了解决方案,看看
  • 谢谢@luke2302。我是一个菜鸟。新的类/结构应该是什么样子
  • @iosmadness 我为你添加了结构
  • 最后我如何调整 addsection 值。他们给了我一个错误。上下文类型 [Item] 不能与字典文字一起使用
  • @iosmadness 创建一个新项目使用Item(description: "Eye brows", number: 100)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多