使用Swift的FileManager遍历文件夹及其子文件夹中的文件

问题描述:

我对Swift编程非常陌生,并且试图遍历文件夹中的文件。
我在此处看了一下答案,并试图将其转换为Swift语法,但没有成功

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
}

我得到的错误是:

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.

使用 nextObject()枚举器的code> 方法:

Use the nextObject() method of enumerator:

while let element = enumerator?.nextObject() as? String {
    if element.hasSuffix("ext") { // checks the extension
    }
}