【问题标题】:Sorting Array values in Dictionary of Swift 3在 Swift 3 字典中对数组值进行排序
【发布时间】:2017-01-22 23:25:05
【问题描述】:

我有一个 .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 键

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

【问题讨论】:

  • 您的代码只对键进行排序。您需要对主字典中的每个单独数组进行排序。
  • 你为什么使用NSArrayNSDictionary等,而不是他们的Swift同行?
  • @NRitH 是的,就像我已经学会了使用索引表视图。我已经实现了这些方法。
  • @rmaddy ...是的,但我该怎么做呢?
  • 我在这里发布回购链接。 github.com/gasparteixeira/TableViewIndexed

标签: ios arrays swift sorting dictionary


【解决方案1】:

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

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"

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

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
    }
}

【讨论】:

    【解决方案2】:

    基于 @Leo-Dabus 的更性能方面的答案是:

    let dict = ["A": ["Angra", "Aerosmith", "ACDC", "Avantasia"],"B": ["Barao Vermelho", "Bon Jovi", "Bee Gees"],"C": ["Cachorro Loco", "Coldplay", "Creed"] ]
    
    let sortedArray2D: [[String]] = dict.keys.sorted().map{ dict[$0]!.sorted() }
    
    print(sortedArray2D)  // "[["ACDC", "Aerosmith", "Angra", "Avantasia"], ["Barao Vermelho", "Bee Gees", "Bon Jovi"], ["Cachorro Loco", "Coldplay", "Creed"]]\n"
    

    这执行得更好,因为编译器现在知道sortedArray2Ddict 具有相同的大小。

    此外,这样sortedArray2D 是一个常量(let),而不是var(允许进一步的性能增强)。

    【讨论】:

    • 编译器怎么知道map返回一个同样大小的数组?是否在某处记录了 swift 编译器围绕 map 进行了特殊优化?
    • 来自developer.apple.com/library/content/documentation/Swift/…。简而言之:map 方法将闭包作为其唯一参数。对数组中的每个项目调用一次闭包,并为该项目返回一个替代映射值(可能是其他类型)。总之:通过使用map,我们为编译器提供了更多关于新数组将是什么的信息。允许它分配正确的内存大小(可能还有我不知道的其他东西)。
    • 问题在于map 内部可能使用var 并调用append 来创建新数组,因此虽然它看起来像是一种优化,但实际上只是包装了相同的过程在函数中,除了方法调用和重复闭包调用的开销。所以有人可能会说它实际上性能较差。
    • 如果我们不告诉编译器新数组的大小,程序将需要不时分配新内存(当我们调用append时)。通过使用map,编译器可以知道新数组的大小,从而消除内存分配开销。
    • @PatrickGoley,来吧,自己尝试一下:swiftlang.ng.bluemix.net/#/repl/57da4349f623dd089776d5c3,在我的测试中,map 至少比 for/append 替代方案快 2 倍。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2021-08-12
    • 1970-01-01
    • 2014-07-28
    相关资源
    最近更新 更多