gpt4 book ai didi

ios - 在 Swift 3 词典中对数组值进行排序

转载 作者:搜寻专家 更新时间:2023-10-31 22:20:26 24 4
gpt4 key购买 nike

我有一个 .plist 文件,其中包含根字典和字母加载键:

["A": ["AXB", "ACD", "ABC"], ... ]

它会是正确的:

["A": ["ABC", "ACD", "AXB"], ... ]

然后,我想对这个数组的 A 索引项进行排序。所以,我试着这样做:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var musicalGroups : NSDictionary = NSDictionary()
var keysOfMusicalGroups : NSMutableArray = NSMutableArray()

override func viewDidLoad() {
super.viewDidLoad()

let bundle = Bundle.main
let path = bundle.path(forResource: "bandas", ofType: "plist")
musicalGroups = NSDictionary(contentsOfFile: path!)!
keysOfMusicalGroups = NSMutableArray(array: musicalGroups.allKeys)
keysOfMusicalGroups.sort(using: NSSelectorFromString("compare:"))

}

我得到了使用 keysOfMusicalGroups.sort 代码排序的 Dictionary 的键

enter image description here

任何帮助将不胜感激。提前致谢!

最佳答案

您只需对字典键进行排序并将排序后的每个值(数组)追加到生成的二维数组中:

let dict = ["A": ["Angra", "Aerosmith", "ACDC", "Avantasia"],"B": ["Barao Vermelho", "Bon Jovi", "Bee Gees"],"C": ["Cachorro Loco", "Coldplay", "Creed"] ]

let sortedArray2D = dict.sorted{ $0.key < $1.key }.map { $0.value.sorted() }

print(sortedArray2D) // "[["ACDC", "Aerosmith", "Angra", "Avantasia"], ["Barao Vermelho", "Bee Gees", "Bon Jovi"], ["Cachorro Loco", "Coldplay", "Creed"]]\n"

您的最终表格 View 应如下所示:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var musicalGroups: [[String]] = []
var musicalTitles: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
let dict = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "bandas", ofType: "plist")!) as? [String: [String]] ?? [:]
musicalTitles = dict.keys.sorted()
musicalGroups = dict.sorted{ $0.key < $1.key }.map { $0.value.sorted() }
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return musicalGroups[section].count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return musicalTitles[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return musicalTitles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "exemplo")
cell.textLabel?.text = musicalGroups[indexPath.section][indexPath.row]
return cell
}
}

关于ios - 在 Swift 3 词典中对数组值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39502568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com