例如,我想检查:Users / username / Desktop /文件夹是否为空,或者更好地检查它是否包含扩展名为.png的文件?
我真的很新,但如果有人知道请帮帮我:)。
答案 0 :(得分:4)
使用contentsOfDirectoryAtPath
获取directoly中所有文件的列表,然后过滤.png
个文件的数组
let path = "/Users/username/Desktop/folder"
do {
let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)
let images = contents.filter { $0.lowercaseString.hasSuffix(".png") }
} catch let error as NSError {
// Directory not exist, no permission, etc.
print(error.localizedDescription)
}
答案 1 :(得分:0)
let fileManager = NSFileManager.defaultManager()
let folderPath = "/Users/username/Desktop/folder"
if let contentEnumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath) {
var numFilesWithSuffix = 0
let mySuffix = "png"
while let fileOrFolder = contentEnumerator.nextObject() as? String {
if fileOrFolder.hasSuffix(mySuffix) {
numFilesWithSuffix += 1 // count occurences
}
}
}