Swift:如何按字母顺序排序,但先用字母排序

时间:2016-12-09 14:30:52

标签: ios swift sorting realm

我有一个Realm结果列表:

subsList = RealmDB.objects(Downloads).filter("isActive = true").sorted("name", ascending: true)

它显示了排序的结果,但第一个结果是"(第1项)"或1项,然后是A项,B项等......

我如何以A-item,B-item等首先出现的方式进行排序?(第1项),最后是1项目显示?

注意:对于那些不了解领域的人,可以采用NSPredicate进行排序

谢谢你们

编辑: 在评论之后,我得到了

-chloro
(+-)-1,2,3-octa
(amino)
1-propanol
acetone
benzin
dinoterb
TNT

我需要

acetone
benzin
dinoterb
TNT
-chloro
(+-)-1,2,3-octa
(amino)
1-propanol

1 个答案:

答案 0 :(得分:0)

这只是一个例子,修复代码使其看起来更好。

var arr = ["-chloro", "(+-)-1,2,3-octa", "(amino)", "1-propanol", "acetone", "benzin","dinoterb","TNT"]

func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0,     length: nsString.length))
        return results.map { nsString.substring(with: $0.range)}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}


arr.sort { (s1, s2) -> Bool in
    let matched = matches(for: "[0-9,\\(,\\-]", in: s1)
    let matched2 = matches(for: "[0-9\\(,\\-]", in: s2)
    if matched.isEmpty && matched2.isEmpty {
        return s1.lowercased() < s2.lowercased()
    } else if matched.isEmpty && !matched2.isEmpty {
        return true
    } else if !matched.isEmpty && matched2.isEmpty {
        return false
    } else {
        return matched.first! < matched2.first!
    }
}

结果 - &gt; [&#34;丙酮&#34;,&#34;苯并&#34;,&#34; dinoterb&#34;,&#34; TNT&#34;,&#34;(+ - ) - 1,2, 3-octa&#34;,&#34;(氨基)&#34;,&#34; -chloro&#34;,&#34; 1-丙醇&#34;]