我有一个字典数组如下所示,我想对它进行排序和存储,以便根据'Like'键的'value'对对象进行排序?我如何在Swift中执行此操作?感谢。
{
Dislike = 0;
Like = 5;
userName = T; }
{
Dislike = 0;
Like = 0;
userName = S; }
{
Dislike = 0;
Like = 10;
userName = N; }
答案 0 :(得分:0)
这个数据结构看起来很奇怪你知道。我认为这是一个[[String: Any]]
。它应该像这样声明:
let data: [[String: Any]] = [
[
"Dislike": 0,
"Like": 5,
"username": "T"],
[
"Dislike": 0,
"Like": 0,
"username": "S"],
[
"Dislike": 0,
"Like": 10,
"username": "N"],
]
要对其进行排序,只需使用sort
功能即可。在闭包中,您应该返回是否应该在第二个参数之前排序第一个参数。在这种情况下,您只想比较与键"Like"
对应的值。闭包体看起来像这样:(伪代码)
firstParameter["Like"] < secondParameter["Like"]
正如我所说,那是伪代码。真正的代码有点复杂:
data.sort { ($0["Like"]! as! Int) < ($1["Like"] as! Int) }
答案 1 :(得分:0)
Sweeper和Edder是对的,它看起来像一组结构。你也可以省略分号。
struct s {
var Dislike: Int = 0
var Like: Int = 0
var userName: String = ""
}
var myArray = [s]()
var i = s()
i.Dislike = 0
i.Like = 5
i.userName = "T"
myArray.append(i)
i.Dislike = 0
i.Like = 0
i.userName = "S"
myArray.append(i)
i.Dislike = 0
i.Like = 10
i.userName = "N"
myArray.append(i)
myArray.sort{$0.Like < $1.Like}