simple? filename sort

given [URL.lastPathComponent] how do I sort as Finder sorts in macOS?

Example: urlPaths = contentsOfDirectory(at: ... e.g., ["1H", "10Ne", "11Na"] urlPaths.sort(by: { $0 < $1 } //Apple Swift version 5.9

print(urlPaths) // 10Ne 11Na 1H

whereas Finder filename sort gives // 1H 10Ne 11 Na

and is beautiful. I have always taken this sort for granted and am now buggered to duplicate it.

Accepted Reply

What you want is a “localized standard compare.” Here’s an example of using it via the SortComparator protocol in the Swift REPL:

  1> import Foundation 
  2> print(["1H", "10Ne", "11Na"].sorted()) 
["10Ne", "11Na", "1H"]
  3> print(["1H", "10Ne", "11Na"].sorted(using: .localizedStandard))
["1H", "10Ne", "11Na"]

Replies

What you want is a “localized standard compare.” Here’s an example of using it via the SortComparator protocol in the Swift REPL:

  1> import Foundation 
  2> print(["1H", "10Ne", "11Na"].sorted()) 
["10Ne", "11Na", "1H"]
  3> print(["1H", "10Ne", "11Na"].sorted(using: .localizedStandard))
["1H", "10Ne", "11Na"]

Armed with Scott's clue, ".localizedStandard", here's what works:

after collecting [URL] with "contentsOfDirectory(at:", parse-out a [String] from the URL components.

apply .sorted(using: .localizedStandard) and use in Picker()

from Picker() use the return value and re-assemble a path to use with "URL(fileWithPath:"

finish-off with JSONDecoder()

Gives a nice Finder-style Picker list and opens the file.

Thanks Scott

Add a Comment