Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through files in a folder and its subfolders using Swift's FileManager

I'm quite new to programming a Swift and I'm trying to iterate through the files in a folder. I took a look at the answer here and tried to translate it to Swift syntax, but didn't succeed.

let fileManager = NSFileManager.defaultManager() let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)  for element in enumerator {     //do something } 

the error I get is:

Type 'NSDirectoryEnumerator' does not conform to protocol 'SequenceType' 

My aim is to look at all the subfolders and files contained into the main folder and find all the files with a certain extension to then do something with them.

like image 449
Iacopo Boccalari Avatar asked Aug 13 '14 11:08

Iacopo Boccalari


2 Answers

Use the nextObject() method of enumerator:

while let element = enumerator?.nextObject() as? String {     if element.hasSuffix("ext") { // checks the extension     } } 
like image 191
pNre Avatar answered Sep 21 '22 22:09

pNre


Nowadays (early 2017) it's highly recommended to use the – more versatile – URL related API

let fileManager = FileManager.default  do {     let resourceKeys : [URLResourceKey] = [.creationDateKey, .isDirectoryKey]     let documentsURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)     let enumerator = FileManager.default.enumerator(at: documentsURL,                             includingPropertiesForKeys: resourceKeys,                                                options: [.skipsHiddenFiles], errorHandler: { (url, error) -> Bool in                                                         print("directoryEnumerator error at \(url): ", error)                                                         return true     })!      for case let fileURL as URL in enumerator {         let resourceValues = try fileURL.resourceValues(forKeys: Set(resourceKeys))         print(fileURL.path, resourceValues.creationDate!, resourceValues.isDirectory!)     } } catch {     print(error) } 
like image 45
vadian Avatar answered Sep 20 '22 22:09

vadian