"sort by name" 个选项的查找器算法

Finder algorithm for "sort by name" options

我使用 NSFileManager class 创建 URL

的集合
let resourceKeys = Set<URLResourceKey>([.nameKey, .isDirectoryKey, .typeIdentifierKey])

let directoryContents = try FileManager.default.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)
let fileURLs = directoryContents.filter { (url) -> Bool in
    do {
        let resourceValues = try url.resourceValues(forKeys: resourceKeys)
        return !resourceValues.isDirectory! && resourceValues.typeIdentifier! == "public.jpeg"
    } catch { return false }
}

下一步我按文件名fileURLs集合排序

let sortedFileURLs = fileURLs.sorted(by: { (URL1: URL, URL2: URL) -> Bool in
    return URL1.pathComponents.last! < URL2.pathComponents.last!
})

它有效,但它不是 Finder 用于“按名称排序”选项(另一个排序结果)的方式 请帮忙!什么算法使用 Finder 进行“按名称排序”

类似Finder的排序顺序可以用localizedStandardCompare

实现

文档说:

This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate.

let sortedFileURLs = fileURLs.sorted{ [=10=].lastPathComponent.localizedStandardCompare(.lastPathComponent) == .orderedAscending }

注:lastPathComponent优于pathComponents.last!