Wil*_*jay 4 nsfilemanager swift
我想要只获得子目录.这是我的数据结构.
根/
我想获取特定文件夹(root)中的目录.我在根文件路径中使用枚举器:
let enumerator = NSFileManager.defaultManager().enumeratorAtPath(filePath)
for element in enumerator! {
print(element)
}
Run Code Online (Sandbox Code Playgroud)
但是,它将迭代root中的每个文件.我怎样才能获得子目录(a&b)?
Leo*_*bus 14
无需使用深枚举.只需获取contentsOfDirectoryAtURL并过滤返回的urls目录.
Xcode 8.2.1•Swift 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 }) ?? []
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
let documentsDirectoryURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let subDirs = documentsDirectoryURL.subDirectories
Run Code Online (Sandbox Code Playgroud)