swift 如何对二维数组中的项进行排序

nr9pn0ug  于 2022-12-22  发布在  Swift
关注(0)|答案(2)|浏览(99)

在下面的代码中,我从字典的值中创建了一个名为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;
}]]
c6ubokkw

c6ubokkw1#

只需将sorted添加到从dictionaryOfItems中提取[Item]的位置:

itemGroups = dictionaryOfItems.keys.sorted().map {
    dictionaryOfItems[$0]!
    .sorted { $0.name > $1.name } // or maybe <
}
3qpi33ja

3qpi33ja2#

要以map的方式更改字典的 values,请使用(等一下)... mapValues
假设我们有:

class Item: CustomStringConvertible {
    var name: String = ""
    init(name: String) { self.name = name }
    var description: String { name }
}

假设我们编了这样一本字典:

dict = ["Group 1": [Item(
        name: "Zipper"
    ), Item(
        name: "Cup"
    ), Item(
        name: "Apple"

    )], "Group 2": [Item(
        name: "Pizza"
    ), Item(
        name: "Bulb"
    ), Item(
        name: "Avocado"
    )]]

那么排序后的字典是

let dictSorted = dict.mapValues{ $0.sorted { $0.name < $1.name} }
    // ["Group 1": [Apple, Cup, Zipper], "Group 2": [Avocado, Bulb, Pizza]]

相关问题