find the size of a file in swift

To find the size of a file in Swift, you can use the FileManager class to get the attributes of the file, which includes its size. Here's an example code snippet:

main.swift
let fileURL = URL(fileURLWithPath: "/path/to/your/file")

do {
    let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path)
    let fileSize = attributes[.size] as! Int64
    print("File size: \(fileSize) bytes")
} catch {
    print("Error: \(error)")
}
277 chars
10 lines

In this code, we create a URL object that represents the file we want to find the size of. We then use FileManager.default to get the attributes of the file at that path. The attributes variable is a dictionary that contains information about the file, including its size. We then use the .size key to access the file size and print it out.

Note that the file size is returned in bytes, so you may want to convert it to a more readable format, such as kilobytes or megabytes, depending on your needs.

gistlibby LogSnag