tableView 中最常见的数组元素

Most common array element in tableView

首先我想说我是 iOS (Swift 2.0) 编码的初学者。所以我有一个数组,我想首先对最常见的元素进行排序,最后对最不常见的元素进行排序。然后我想将其插入到 UITableView 中,其中最常见的项目应显示在顶部,最不常见的项目应显示在底部。因此,如果我在数组中有一个名为 "Food" 的项目并且它出现了 3 次,它应该位于出现 2 次的名为 "Candy" 的项目之上。谢谢!

编辑: 很抱歉提出了一个如此糟糕的问题,正如我所说,我是编程的初学者,所以我也不是最擅长解释我的情况的人。但这次我会尝试更好地描述我的情况。首先,我想先用最常见的元素对我的数组进行排序,然后是第二个最常见的元素,依此类推。 John 提供的答案帮助我做到了这一点,之后我设法将其放入 tableView 中,如下所示:

 var counts : Dictionary<String, Int> = Dictionary<String, Int>()


override func viewDidLoad() {

    for (_, value) in prioLista.enumerate() {

        if let count = counts[value] {

            counts[value] = count + 1

        }
        else {
            counts[value] = 1
        }

    }

    prioLista.sortInPlace { (first, second) -> Bool in

        let firstCount = counts[first]
        let secondCount = counts[second]

        return firstCount > secondCount
    }

  navigationItem.title = "Spara"

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return prioLista.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellster = tableView.dequeueReusableCellWithIdentifier("cellster")


    cellster?.textLabel?.text = prioLista[indexPath.row]

    return cellster!
}

代码中包含的变量 prioLista 是来自另一个文件的数组。通过按下按钮,您可以将字符串添加到其中。

My tableView after sorting elements after most common

这就是我现在所在的位置,如图所示。 tableView 按照我的意愿对元素进行排序。但是,我希望每个不同的对象只有一行。因此,如果数组包含的 "Mat" 多于 "Godis",我仍然希望 "Mat" 高于 "Godis",但我希望它们各占一行。截至目前,tableView 显示了我数组中的每个项目,相反我希望它删除重复项,但仍然优先考虑最常见的项目,使其位于不太常见的项目之上。我知道我想删除项目但仍使用 John 提供的功能听起来可能很奇怪,但如果有办法做到这一点,我会很高兴。

所以现在总结一下我真正想要的,所以我会尽可能清楚地说明这一点;在我链接的图片中,我的对象按它们的常见程度排序,我想知道是否有一种方法可以只显示一个相同的对象,但仍然以这种方式对数组进行排序。因此,如果 "Mat" 多于 "Godis",则应显示为:

第一排:Mat 第二排:Godis

在表格视图中

我希望我已经足够清楚了,提醒一下,我只是一个正在尝试学习编码的初学者:)

可能有几种方法可以实现这一点,但这里有一个例子。首先获取字符串在数组中出现的次数,然后将其存储在字典中。然后使用该字典对数组进行排序:

let arr = ["Food", "Candy", "Food", "Candy", "Food"]

var counts : Dictionary<String, Int> = Dictionary<String, Int>()

for (index, value) in arr.enumerate() {

    if let count = counts[value]{

        counts[value] = count + 1

    }
    else{
        counts[value] = 1
    }

}

let sorted = arr.sort { (first, second) -> Bool in

    let firstCount = counts[first]
    let secondCount = counts[second]

    return firstCount > secondCount

}