使用字典表数据Swift

时间:2018-02-01 17:47:52

标签: swift uitableview dictionary swift4

我的字典会根据用户选择的选项而变化。例如:

[" Item1":7," Item2":4," Item3":4," Item4":7,&# 34; Item5":6]

每个项目旁边的数字是每个项目的计数。我想知道如何将这个词典转换成表格?所以在左栏中是项目,在右栏中是项目计数?

最好的方法是什么?

数据最初是一个格式为["Item1", "Item2", "Item3", "Item1", "Item1", "Item2"]的数组。

但是我用了

var counts: [String: Int] = [:] , myArray.forEach { counts[$0, default: 0] += 1 }

计算数组中的每个项目

2 个答案:

答案 0 :(得分:1)

You can transform your dictionary into a sorted array like this:

let array = data.map { $0 }.sorted { $0.key < $1.key }

This will result in an array of (key: String, value: Int) sorted alphabetically by the keys.

Now, in your tableView delegate methods you can return array.count to get the number, and if you want to configure your cell you can do something like this:

let element = array[indexPath.row]
cell.textLabel.text = element.key
cell.detailLabel.text = "\(element.value)"

答案 1 :(得分:1)

So, for a tableview data source, you want an array.

var dic = ["Item1": 7, "Item2": 4, "Item3": 4, "Item4": 7, "Item5": 6]
var tableInfo = [(String, Int)]()

for (k, v) in dic {
    let temp = (k, v)
    tableInfo.append(temp)
}

Revised per OP's comments.

Now you have an array of tuples suitable for sorting and use in your tableview delegate.