find the size of a json file in swift

To find the size of a JSON file in Swift, you can use the following code:

main.swift
let fileUrl = Bundle.main.url(forResource: "example", withExtension: "json")
do {
    let fileSize = try FileManager.default.attributesOfItem(atPath: fileUrl.path)[FileAttributeKey.size] as! UInt64
    print("Size of file: \(fileSize) bytes")
} catch {
    print("Error: \(error)")
}
284 chars
8 lines

In this code, we first get the URL of the JSON file using the Bundle class. We then use the FileManager.default instance to get the attributes of the file using its path. The size of the file is stored as a UInt64 value in the attributesOfItem dictionary, which we extract using the as! operator. Finally, we print the size of the file in bytes.

Note that this code assumes that the JSON file is located in the main bundle of the app. If the file is located in a different location, you may need to modify the code to use a different file URL.

gistlibby LogSnag