在下面的代码中,我从字典的值中创建了一个名为itemGroups
的二维数组,除了没有按字母顺序排序的项之外,其他一切都按预期工作。
如何对itemGroups
二维数组中的项进行排序?调用map()
时有没有办法?
class Item{
var name:String = ""
}
var itemGroups: [[Item]] = []
func createGroupsOfItems(){
// dictionary signature just for reference
var dictionaryOfItems:Dictionary = [String: [Item]]()dictionaryOfItems
// add arrays of items from the dictionary values
/// here I need to sort the items within the nested arrays
itemGroups = dictionaryOfItems.keys.sorted().map({ dictionaryOfItems[$0]!})
print("Groups Output: \(sectionsOfItems)") // see output below
print("Dictionary Output: \(sectionForCategory)")// see output below, just for reference
}
组输出
Groups Output:
[[Item {
name = Zipper;
}, Item {
name = Cup;
}, Item {
name = Apple;
}], [Item {
name = Pizza;
}, Item {
name = Bulb;
}, Item {
name = Avocado;
}]]
字典输出
Dictionary Output:
["Group 1": [Item {
name = Zipper;
}, Item {
name = Cup;
}, Item {
name = Apple;
}], "Group 2": [Item {
name = Pizza;
}, Item {
name = Bulb;
}, Item {
name = Avocado;
}]]
排序后的所需组输出
Groups Output:
[[Item {
name = Apple;
}, Item {
name = Cup;
}, Item {
name = Zipper;
}], [Item {
name = Avocado;
}, Item {
name = Bulb;
}, Item {
name = Pizza;
}]]
2条答案
按热度按时间c6ubokkw1#
只需将
sorted
添加到从dictionaryOfItems
中提取[Item]
的位置:3qpi33ja2#
要以
map
的方式更改字典的 values,请使用(等一下)...mapValues
!假设我们有:
假设我们编了这样一本字典:
那么排序后的字典是