Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.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
Swift 如何按值对字典排序?_Swift_Sorting_Dictionary - Fatal编程技术网

Swift 如何按值对字典排序?

Swift 如何按值对字典排序?,swift,sorting,dictionary,Swift,Sorting,Dictionary,我的字典是这样的: var items = [Int: [String]]() var itemsResult = [Int: [String]]() dictionaries.sorted(by: { $0["name"] < $1["name"] }) itmesResult存储从服务器下载的数据。 并将数据传递给items use of items=itmesResult 该值有3个元素,如[“Apple”、“/image/Apple.png”、“29”] 我想根据第一个值对字

我的字典是这样的:

var items = [Int: [String]]() 
var itemsResult = [Int: [String]]()
dictionaries.sorted(by: { $0["name"] < $1["name"] })
itmesResult存储从服务器下载的数据。 并将数据传递给items use of items=itmesResult

该值有3个元素,如[“Apple”、“/image/Apple.png”、“29”] 我想根据第一个值对字典进行排序,这是Apple

for (k,v) in (itemsResult.sorted(by: { $0.value[0] < $1.value[0] })) { 
  items[k] = v
}
分类:

2:["AAA","/image/aaa.png","29"]
1:["Apple","/image/apple.png","29"]
3:["Banana","/image/banana.png","29"]

我想按第一个值对其进行排序。

与其将这些变量保存到数组中,不如将它们设置为字典数组

您可以这样做:

var dictionaries:[Dictionary<String, String>] = []
for item in items {
  let dictionary = {"name": item[0], "url": item[1], "id" : item[2]}
  dictionaries.append(dictionary)
}
var字典:[字典]=[]
对于项目中的项目{
let dictionary={“name”:项[0],“url”:项[1],“id”:项[2]}
字典。附加(字典)
}
您可以按如下方式获得已排序的词典列表:

var items = [Int: [String]]() 
var itemsResult = [Int: [String]]()
dictionaries.sorted(by: { $0["name"] < $1["name"] })
字典。排序(按:{$0[“name”]<$1[“name”]})

因此,如果我以你为例,这就做到了:

var items = [Int: [String]]()

items[0] = ["Apple","/image/apple.png","29"]
items[1] = ["AAA","/image/aaa.png","29"]
items[2] = ["Banana","/image/banana.png","29"]

let itemResult = items.sorted { (first: (key: Int, value: [String]), second: (key: Int, value: [String])) -> Bool in
    return first.value.first! < second.value.first!
}

print (itemResult)
编辑:
还要注意,这种情况实际上并没有对字典进行“排序”,因为字典是按定义排序的,而不是按定义排序的,这会创建一个使用数组索引排序的键值对象数组。

字典是按定义无序的。@yz\,是否要对数组中的值进行排序?我刚刚更新了问题。是否确实正确解释了数据?因为,在我看到的数据中,
[“AAA”、“/image/AAA.png”、“29”]
应该是一个对象(或结构),具有name属性、imageURL和另一个表示29.No的属性。这是一个数组。但如果使用对象或结构可以很容易地解决它,我可以改变。