1

我一直在使用 Swift 的[enumerator(at:includingPropertiesForKeys:options:)]1来查找给定基本路径中的所有文件,并为不同的资源键(文件名、路径、创建日期等)创建数组。这工作得很好,但我注意到创建的数组中的元素不是按创建日期排序的,这是我在将这些数组的元素传递到循环中以按日期顺序上传每个文件之前需要的。

因此,我需要以某种方式按创建日期对所有结果数组的元素进行排序,这是我能够在其自己的数组中提取的属性(使用 .creationDateKey 资源键)。因此,我有两个选择(我认为):

  1. 强制元素按其创建日期首先附加到原始数组
  2. 使用包含文件创建日期的数组对每个创建的数组的元素进行排序

最好的方法是什么?我认为这很简单,但没有发现它。

所有的建议都亲切地接受了。谢谢。

这是我的代码:

        // get URL(s) and other attributes of file(s) to be uploaded
        let localFileManager = FileManager()
        let resourceKeys = Set<URLResourceKey>([.nameKey, .pathKey, .creationDateKey, .isDirectoryKey])
        let directoryEnumerator = localFileManager.enumerator(at: baseURL, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)!
         
        var fileURLs: [URL] = []
        var fileNames: [String] = []
        var filePaths: [String] = []
        var fileDates: [Date] = []
        for case let fileURL as URL in directoryEnumerator {
            guard let resourceValues = try? fileURL.resourceValues(forKeys: resourceKeys),
                let isDirectory = resourceValues.isDirectory,
                let name = resourceValues.name,
                let path = resourceValues.path,
                let date = resourceValues.creationDate,
                else {
                    continue
            }
            if isDirectory {
                if name == "_extras" { // use this to exclude a given directory
                    directoryEnumerator.skipDescendants()
                }
            } else {
                
                // append elements in date order here?
                
                fileURLs.append(fileURL) // full URLs of files
                fileNames.append(name) // file names only
                filePaths.append(path) // paths of file
                fileDates.append(date) // date and time that file was created
                
                // sort arrays by creation date here?
                
            }
        }
        print(fileURLs)
        print(fileNames)
        print(filePaths)
        print(fileDates)
4

1 回答 1

4

您不应该为此使用多个数组,而是将您的值包装在自定义结构中

struct FileInfo {
    let url: URL
    let name: String
    let path: String //this is not really needed, you can get it from the url
    let date: Date
}

并为此设置一个数组

var files: [FileInfo]()

并创建您的结构实例并附加它

files.append(FileInfo(url: fileURL, name: name, path: path, date: date)

排序现在将是微不足道的,所以在你做的 for 循环之后

files.sort(by: { $0.date < $1.date })

这是按升序排列的,不确定你想要哪一个。

于 2022-01-04T10:29:30.473 回答