Swift 2 iOS – 按创建日期排序的文件列表 – 更简洁的解决方案?

前端之家收集整理的这篇文章主要介绍了Swift 2 iOS – 按创建日期排序的文件列表 – 更简洁的解决方案?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的代码中,我正在返回一个[String]?包含存储在/ Documents / – 的文件名(lastPathComponent),按照上次修改的日期排序.

我相信我可能使用太多的步骤,并在这里寻找建议,如何减少代码.

为了达到目前所需的结果 – 我正在创建两个中间词典:var attributesDictionary:[String:AnyObject]?和var urlDictionary = [NSURL:NSDate]().循环通过初始[NSURL]我使用两个步骤 – .resourceValuesForKeys初始化attributesDictionary.然后填入urlDictionary,使其包含URL和NSURLContentModificationDateKey关键字的值.

我觉得应该有一种方法来实现这个结果,而不必创建urlDictionary和attributesDictionary,而不需要循环.也许从urlArray直接.这是我当前的代码

编辑:Arthur Gevorkyan在第一条评论中指出,do {}不是必需的.

func getFileList() -> [String]? {
    let directory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains: .UserDomainMask)[0]
    let properties = [NSURLLocalizedNameKey,NSURLCreationDateKey,NSURLContentModificationDateKey,NSURLLocalizedTypeDescriptionKey]

    // no catch required - contentsOfDirectoryAtURL returns nil if there is an error
    if let urlArray = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(directory,includingPropertiesForKeys: properties,options:NSDirectoryEnumerationOptions.SkipsHiddenFiles) {
        var attributesDictionary: [String:AnyObject]?
        var dateLastModified: NSDate
        var urlDictionary = [NSURL:NSDate]()

        for URLs in urlArray {
            // no catch required - resourceValuesForKeys returns nil if there is an error
            attributesDictionary = try? URLs.resourceValuesForKeys(properties)
            dateLastModified = attributesDictionary?[NSURLContentModificationDateKey] as! NSDate
            urlDictionary[URLs] = dateLastModified
        }
        // this approach to sort is used because NSDate cannot be directly compared with </>
        return urlDictionary.filter{$0 != nil}.sort{$0.1.compare($1.1) == NSComparisonResult.OrderedDescending }.map{$0.0}.map{$0.lastPathComponent!}
    } else {
        return nil
    }
}
可能的解决方案:
if let urlArray = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(directory,options:.SkipsHiddenFiles) {

    return urlArray.map { url -> (String,NSTimeInterval) in
        var lastModified : AnyObject?
        _ = try? url.getResourceValue(&lastModified,forKey: NSURLContentModificationDateKey)
        return (url.lastPathComponent!,lastModified?.timeIntervalSinceReferenceDate ?? 0)
    }
    .sort({ $0.1 > $1.1 }) // sort descending modification dates
    .map { $0.0 } // extract file names

} else {
    return nil
}

URL数组首先映射到(lastPathComponent,lastModificationDate)元组的数组,然后按照
最后修改日期,最后提取路径名.

attributesDictionary可以通过使用来避免
getResourceValue(_:forKey)仅检索最后一个修改日期.

Swift 3的更新:

let directory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!
if let urlArray = try? FileManager.default.contentsOfDirectory(at: directory,includingPropertiesForKeys: [.contentModificationDateKey],options:.skipsHiddenFiles) {

    return urlArray.map { url in
            (url.lastPathComponent,(try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? Date.distantPast)
        }
        .sorted(by: { $0.1 > $1.1 }) // sort descending modification dates
        .map { $0.0 } // extract file names

} else {
    return nil
}

猜你在找的Swift相关文章