ios - 如何通过比较swift中的每个字符来排序?

标签 ios arrays swift sorting

抱歉,我有一个关于排序数据的问题。
我不知道如何对每个字符进行排序,我只是按第一个字符排序,如下图所示。
如何对每个部分数组中的字符进行排序。
谢谢。

enter image description here

var cityCollation: UILocalizedIndexedCollation? = nil
var sectionsCityArray = [[City]]()
var cityArray:[City] = [City]() //cityArray is my original data that is not sorting 

func configureSectionCity() { 

    cityCollation = UILocalizedIndexedCollation.current()

    let sectionTitlesCount = cityCollation!.sectionTitles.count

    var newSectionsArray = [[City]]()

    for _ in 0..<sectionTitlesCount {
        let array = [City]()
        newSectionsArray.append(array)
    }

    for bean in cityArray {
        let sectionNumber = cityCollation?.section(for: bean, collationStringSelector: #selector(getter: City.name))
        var sectionBeans = newSectionsArray[sectionNumber!]

        sectionBeans.append(bean)
        newSectionsArray[sectionNumber!] = sectionBeans
    }

  sectionsCityArray = newSectionsArray

  }

最佳答案

假设 City 对象有一个 name 属性并且您想要顺序 q001, q002, q004, q005, q010, q012 你可以用

newSectionsArray[sectionNumber!] = sectionBeans.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }

localizedStandardCompare 需要 Foundation 框架

关于ios - 如何通过比较swift中的每个字符来排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47198744/

相关文章:

javascript - Bluebird 对一系列功能的 promise

ios - 实现 iOS 版 Google 登录 (Swift 2.0)

ios - 在 iOS 中匹配按钮框架

ios - updateValue 不适用于字典

ios - Q :Controller present 2 second ,如何让它看起来只有一个转换?

ios - 正确转换字节值

ios - 如何在 iOS 7.1 中对联系人进行排序

java - 如何在数组中添加 40 以下的数字

java - 文件内容到字节数组?

ios - Swift 3 button.addTarget 不适用于所有表格单元格