-1

I have an array of pdf files (see attached screenshot) that I need to sort alphabetically. Here is the code that generates the array, can anybody suggest changes to have the array sorted?

import UIKit

var pdfsArray = [String]()

class PDFListViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let fm = FileManager.default
        
        let path = Bundle.main.resourcePath!

        let items = try! fm.contentsOfDirectory(atPath: path)
        
        for item in items {
            if item.hasSuffix(".pdf") {
               
                pdfsArray.append(item.uppercased())
                
            }
            let sortedFiles = pdfsArray.sorted()
             pdfsArray = sortedFiles
        }

enter image description here

3
  • Please add your image Commented May 28, 2021 at 8:05
  • 1
    Sorted how, what is wrong with the current solution? Commented May 28, 2021 at 8:09
  • You shouldn't declare your variables at global scope. Search how to pass your data from one view controller to another. Commented May 28, 2021 at 19:01

1 Answer 1

0

Simple enough, you can just call swift's sort (or sorted) function and provide the sort-function to sort by numeric values:

var array = ["Part 45", "Part 1", "Part 10", "Part 20", "Part 100", "Part 2"]
array.sort { st1, st2 in
    st1.compare(st2, options: .numeric) == .orderedAscending
}
Sign up to request clarification or add additional context in comments.

5 Comments

How can I display just the file names without the pdf extension in the array?
Prefer using URL at top level instead of path String and you'll be able to use deletingPathExension() ?
@SkyCruzer using URL resourceValues's method and get localizedName value. If you want to hide the extension you can set the url resourceValue hasExtensionHidden to true
@SkyCruzer Btw when sorting files to display it to the user like the finder does, you should use the diacritic and case insensitive localizedStandardCompare method. This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact sorting behavior of this method is different under different locales and may be changed in future releases. This method uses the current locale.
Thank you so much all. I am new in this world of app development and I appreciate all your responses. Great working with you all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.