2015-12-21 37 views
1

我试图获取子目录。这是我的数据结构。使用Swift获取子目录

根/

  • 一个/
    • 的1.txt
    • 2.txt
  • B/
    • 3.txt
    • 4.txt

我想在一个特定的文件夹(根)目录。我在根文件路径中使用枚举器:

let enumerator = NSFileManager.defaultManager().enumeratorAtPath(filePath) 
for element in enumerator! { 
    print(element) 
} 

但是,它会迭代root中的每个文件。我怎样才能得到子目录(一个& b)?

+0

目前还不清楚你在问什么。您是否只列出位于特定文件夹中的目录? –

+0

是的。我试图在特定文件夹中获取目录 – WeiJay

+0

无需使用深层枚举器,只需获取该目录的内容并过滤返回的目录即目录 –

回答

8

没有必要使用深度枚举。只需获取contentsOfDirectoryAtURL并过滤返回的目录即urls。

的Xcode 8.2.1•斯威夫特3.0.2

extension URL { 
    var isDirectory: Bool { 
     return (try? resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true 
    } 
    var subDirectories: [URL] { 
     guard isDirectory else { return [] } 
     return (try? FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]).filter{ $0.isDirectory }) ?? [] 
    } 
} 

用法:

let documentsDirectoryURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) 

let subDirs = documentsDirectoryURL.subDirectories