Get all resource paths in bundle recursively

I’ve been looking for a way to search a subdirectory in my main bundle recursively – the following simple Swift extension does the trick.

I’ve been looking for a way to search a subdirectory in my main bundle recursively – the following simple Swift extension does the trick.

Bundle.main.paths(forResource: String?, ofType: String?) -> [String]?


let paths: [String]? = Bundle.main.paths(forResource: "my-resource", ofType: "my-extension")

Bundle.main.urls(forResource: String?, withExtension: String?) -> [URL]?

let urls: [URL]? = Bundle.main.urls(forResource: "my-resource", withExtension: "my-extension")

The source code of the extension

import Foundation

extension Bundle{
    
    func urls(forResource name: String?, withExtension ext: String?) -> [URL]?{
        guard let resourceURL = self.resourceURL else{ return nil }
        let enumerator = FileManager.default.enumerator(at: resourceURL, includingPropertiesForKeys: nil)
        
        var urls = [URL]()
        while let url = enumerator?.nextObject() as? URL{
            guard ext == nil && url.lastPathComponent == name || ext == url.pathExtension && url.deletingPathExtension().lastPathComponent == name else{
                continue
            }
            urls.append(url)
        }
        
        return urls.count > 0 ? urls : nil
    }
    
    func paths(forResource name: String?, ofType type: String?) -> [String]?{
        return self.urls(forResource: name, withExtension: type)?.map{ $0.path }
    }
}