Ask Your Question
0

How can I rapidly determine the size of a directory using Swift?

asked 2022-07-28 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-11-07 04:00:00 +0000

qstack gravatar image

You can use the FileManager class in Swift to determine the size of a directory:

func calculateDirectorySize(at url: URL) -> Int64 {
    let fileManager = FileManager.default
    var folderSize: Int64 = 0

    guard fileManager.fileExists(atPath: url.path) else { return folderSize }

    do {
        let files = try fileManager.contentsOfDirectory(atPath: url.path)
        for file in files {
            let path = url.appendingPathComponent(file).path
            let attributes = try fileManager.attributesOfItem(atPath: path)
            folderSize += attributes[FileAttributeKey.size] as! Int64
        }
    } catch {
        print("Error while enumerating files \(url.path): \(error.localizedDescription)")
    }

    return folderSize
}

You can call this function with the URL of the directory you want to determine the size of:

let directoryURL = URL(fileURLWithPath: "/Users/Username/Documents/")
let size = calculateDirectorySize(at: directoryURL)
print("Directory size: \(size)")

This function will calculate the total size of all the files within the directory, including any subdirectories.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-28 11:00:00 +0000

Seen: 18 times

Last updated: Nov 07 '22