Search code examples
swiftsortingurlnsfilemanagerfinder

Finder algorithm for "sort by name" options


Im use NSFileManager class to create collection of 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 }
}

the next step Im sorted fileURLs collection by file name

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

it works, but it's not the way as used Finder for "sort by name" options (another sorted result) Please help! What algorithm used Finder for "sort by name"


Solution

  • The Finder-like sort order can be realized with localizedStandardCompare

    The documentation says:

    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{ $0.lastPathComponent.localizedStandardCompare($1.lastPathComponent) == .orderedAscending }
    

    Note: lastPathComponent is preferable over pathComponents.last!