find the size of a directory in swift

To find the size of a directory in Swift, we can take the following steps:

  1. We need to create a function that will recursively iterate through all directories and files of the given path.
  2. For each file, we can gather its attributes using FileManager API.
  3. We can check if it's a file or directory. If it is a file, we can add its file size to the accumulating size.
  4. If it is a directory, we will recursively look at all the files and directories inside of it until we find all the file sizes.
  5. Finally, we will return the total file size of the directory.

Here's a sample implementation:

main.swift
func getDirectorySize(path: String) -> UInt64 {
    let fileManager = FileManager.default
    var isDirectory: ObjCBool = false
    var size: UInt64 = 0

    if fileManager.fileExists(atPath: path, isDirectory: &isDirectory) {
        if isDirectory.boolValue {
            if let files = fileManager.enumerator(atPath: path) {
                while let file = files.nextObject() as? String {
                    let filePath = "\(path)/\(file)"
                    do {
                        let attr = try fileManager.attributesOfItem(atPath: filePath)
                        if let fileSize = attr[FileAttributeKey.size] as? UInt64 {
                            size += fileSize
                        }
                    } catch {
                        print("Error: \(error)")
                    }
                }
            }
        } else {
            do {
                let attr = try fileManager.attributesOfItem(atPath: path)
                if let fileSize = attr[FileAttributeKey.size] as? UInt64 {
                    size += fileSize
                }
            } catch {
                print("Error: \(error)")
            }
        }
    } else {
        print("Directory does not exist")
    }

    return size
}
1249 chars
37 lines

To use this function, you can call it with a path to the directory:

main.swift
let directoryPath = "/path/to/directory"
let size = getDirectorySize(path: directoryPath)
print("Directory size: \(size) bytes")
129 chars
4 lines

gistlibby LogSnag