如何使用比较器签名创建 NSSortDescriptor?

How to create an NSSortDescriptor using the comparator signature?

我可以像这样创建不区分大小写的字符串排序描述符:

let titleSort = NSSortDescriptor(key: "title", ascending: true,
                                     selector: #selector(NSString.localizedCaseInsensitiveCompare))

我似乎不知道如何使用 comparator 签名:

class NSSortDescriptor {
  init(key: String?, ascending: Bool, comparator cmptr: @escaping Foundation.Comparator)
  ...
}

我是否必须从头开始创建一个新的比较器,或者 String 已经存在一些东西?

TIA

示例:

class C : NSObject {
    var id = 0
}

let desc = NSSortDescriptor(key: "id", ascending: true) { // comparator function
    id1, id2 in
    if (id1 as! Int) < (id2 as! Int) { return .orderedAscending }
    if (id1 as! Int) > (id2 as! Int) { return .orderedDescending }
    return .orderedSame
}

// test:

let c1 = C(); let c2 = C(); let c3 = C()
c1.id = 100; c2.id = 50; c3.id = 25
let arr = [c1,c2,c3]
let arr2 = (arr as NSArray).sortedArray(using: [desc])

没有用于此的全局函数,因为 Comparator 旨在执行非内置的比较。它非常灵活,因为它允许您比较 2 种不同类型的对象并准确定义您希望它们如何排序。在一个关于如何对它们进行排序的非常简单的演示中,我创建了一个示例,首先检查传入的两个对象是否为 String,如果不是,我就将它们视为应该同时排序等级。否则我按字母顺序对它们进行排序(不区分大小写,因为我将它们变成小写)。显然,您可以根据您预期需要排序的内容将其设置得尽可能复杂:

let descriptor = NSSortDescriptor(key: "title", ascending: true) { (string1, string2) -> ComparisonResult in
        guard let s1 = string1 as? String, let s2 = string2 as? String else {
            return ComparisonResult.orderedSame
        }
        if s1.lowercased() < s2.lowercased() {
            return ComparisonResult.orderedAscending
        } else if s1.lowercased() == s2.lowercased() {
            return ComparisonResult.orderedSame
        } else {
            return ComparisonResult.orderedDescending
        }
    }