Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/106.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用字典在Swift 4中填充UITableView数据_Ios_Swift_Xcode_Dictionary_Tableview - Fatal编程技术网

Ios 使用字典在Swift 4中填充UITableView数据

Ios 使用字典在Swift 4中填充UITableView数据,ios,swift,xcode,dictionary,tableview,Ios,Swift,Xcode,Dictionary,Tableview,我目前正在尝试使用字典中的数据填充UITableView。我收到一个错误“无法为“Dictionary”类型的值下标”。我知道这意味着什么,但我不知道如何修复它。我知道如何使它与数组一起工作。可以用字典吗 // my dictionary var contactDictionary: Dictionary = [String: String]() //function that throws error func tableView(_ tableView: UITableView, c

我目前正在尝试使用字典中的数据填充UITableView。我收到一个错误“无法为“Dictionary”类型的值下标”。我知道这意味着什么,但我不知道如何修复它。我知道如何使它与数组一起工作。可以用字典吗

// my dictionary 

var contactDictionary: Dictionary = [String: String]()

//function that throws error

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "contactcell", for: indexPath) as! UITableViewCell
  let object = contactDictionary[indexPath.row]

}

您可以使用contactDictionary.keys检索键数组并使用键查找值,但顺序可能会每次都更改;Swift不保证字典的顺序。如果顺序很重要,您可以搜索第三方OrderedDictionary或其他数据结构

您只需将字典声明代码从

var contactDictionary: Dictionary = [String: String]()

正如注释词典中已经提到的,它是一个无序的集合。如果需要对其进行排序,可以使用键值对数组:

var contacts: [(key: String, value: String)] = []

字典是无序的,通过键而不是整数索引访问。我建议您将密钥提取到一个数组中,并使用该数组从字典中访问相关对象。好的,我想我明白了。在这种情况下,秩序并不重要,所以应该是有效的。谢谢
var contactDictionary: [String: String] = [:]
var contacts: [(key: String, value: String)] = []