Swift:如何使所选单元格从字典中记录相应的值和键

Swift:如何使所选单元格从字典中记录相应的值和键,swift,nsdictionary,tableview,Swift,Nsdictionary,Tableview,我有一个由字典填充的TableViewController。我的目标是,当我从tableView中单击一个单元格时,它将从字典中记录该单元格的名称以及相应的值 例如,如果我有一本字典: var profiles=[“乔”:1,“萨姆”:2,“南希”:3,“弗雷德”:4,“露西”:5] 当我点击Sam时,它会显示“Sam.2”或类似的内容。 任何帮助都会很好 下面是我的代码示例(TableView): 这是我的swift文件: class people { var profiles = ["Joe

我有一个由字典填充的TableViewController。我的目标是,当我从tableView中单击一个单元格时,它将从字典中记录该单元格的名称以及相应的值

例如,如果我有一本字典:
var profiles=[“乔”:1,“萨姆”:2,“南希”:3,“弗雷德”:4,“露西”:5]

当我点击Sam时,它会显示“Sam.2”或类似的内容。 任何帮助都会很好

下面是我的代码示例(TableView):

这是我的swift文件:

class people {
var profiles = ["Joe": 1, "Sam": 2, "Nancy": 3, "Fred": 4, "Lucy": 5]
var typeList:[String] { //computed property 7/7/14
    get{
        return Array(profiles.keys)
    }





    }

我将获取标签中的文本,并使用它搜索字典:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

   // Get the cell for that indexPath
   var cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!

   // Get that cell's labelText
   let myKey = cell.textLabel?.text

   // Output the key and it's associated value from the dictionary
   println("\(myKey): \(person.typeList[myKey])")

}

因此,理想情况下,您希望使用该方法提供的索引路径来获取选择的任何单元格

一旦你有了它,你就可以从单元格中提取文本并用字典检查

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    // Lots of optional chaining to make sure that nothing breaks
    if let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath) { // Get the cell
        if let cellTextLabel: UILabel = cell.textLabel { // Get the cell's label
            if let name: String = cellTextLabel.text { // Get the text from its label
                println("\(name): \(profiles[name])") // Check with the dictionary and print out the corresponding value
            }

        }
    }
}

//我就在这里
很好。但我没有看到你记录任何东西。有什么问题吗?
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    // Lots of optional chaining to make sure that nothing breaks
    if let cell: UITableViewCell = tableView.cellForRowAtIndexPath(indexPath) { // Get the cell
        if let cellTextLabel: UILabel = cell.textLabel { // Get the cell's label
            if let name: String = cellTextLabel.text { // Get the text from its label
                println("\(name): \(profiles[name])") // Check with the dictionary and print out the corresponding value
            }

        }
    }
}