繁体   English   中英

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

[英]Using a dictionary to populate a UITableView data in Swift 4

我目前正在尝试用字典中的数据填充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 contactDictionary = [String: String]()

要么

var contactDictionary: [String: String] = [:]

正如评论中已经提到的,Dictionary是无序集合。 如果需要保持排序,可以使用键值对数组:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM