title: Swift 2 iOS - get file list sorted by creation date - more concise solution?
body: <p>In my code, which works, I am returning a <code>[String]?</code> containing the names of the files (<code>lastPathComponent</code>) stored in <code>/Documents/</code> - ordered by the date last modified.</p>
  
  <p>I believe that I am probably using too many steps and am looking for advice here re how to reduce the code.</p>
  
  <p>In order to achieve the required result currently - I am creating two intermediate dictionaries: <code>var attributesDictionary: [String : AnyObject]?</code> and <code>var urlDictionary = [NSURL:NSDate]()</code>. Looping through the initial <code>[NSURL]</code> I am using two steps - <code>.resourceValuesForKeys</code> initializes <code>attributesDictionary</code>. I then populate <code>urlDictionary</code> so that it contains the URL and the value for the key <code>NSURLContentModificationDateKey</code>.</p>
  
  <p>I feel fairly certain that there should be a way to achieve this result without creating <code>urlDictionary</code> and <code>attributesDictionary</code> and without the need for the loop. Perhaps from <code>urlArray</code> directly. Here is my current code:</p>
  
  <p>EDIT: <code>do{}</code>s were not required as pointed out by Arthur Gevorkyan in the first comment.</p>
  
  <pre><code>func getFileList() -&gt; [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 &lt;/&gt;
          return urlDictionary.filter{$0 != nil}.sort{$0.1.compare($1.1) == NSComparisonResult.OrderedDescending }.map{$0.0}.map{$0.lastPathComponent!}
      } else {
          return nil
      }
  }
  </code></pre>