使用 Swift 获取子目录 [英] Get Subdirectories using Swift

查看:83
本文介绍了使用 Swift 获取子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅获取子目录.这是我的数据结构.

I'm trying to get ONLY subdirectories. Here's my data structure.

根/

  • a/
    • 1.txt
    • 2.txt
    • 3.txt
    • 4.txt

    我想获取特定文件夹(根)中的目录.我在根文件路径中使用枚举器:

    I want to get directories in a specific folder(root). I use enumerator in root file path:

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

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

    However, It will iterate every files in root. How can I get just subdirectories (a&b) ?

    推荐答案

    没有必要使用深枚举.只需获取 contentsOfDirectoryAtURL 并过滤返回的目录 url.

    There is no need to use a deep enumeration. Just get contentsOfDirectoryAtURL and filter the urls returned which are directories.

    Xcode 11.4• Swift 5.2

    extension URL {
        func subDirectories() throws -> [URL] {
            // @available(macOS 10.11, iOS 9.0, *)
            guard hasDirectoryPath else { return [] }
            return try FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]).filter(\.hasDirectoryPath)
        }
    }
    


    用法:


    usage:

     do {
        let documentsDirectory =  try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let url = documentsDirectory.appendingPathComponent("pictures", isDirectory: true)
        if !FileManager.default.fileExists(atPath: url.path) {
            try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false, attributes: nil)
        }
        let subDirs = try documentsDirectory.subDirectories()
        print("sub directories", subDirs)
        subDirs.forEach { print($0.lastPathComponent) }
    } catch {
        print(error)
    }
    

    这篇关于使用 Swift 获取子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆