find the name of a json file in swift

To find the name of a JSON file in Swift, you can use the URL class to get a reference to the file URL, and then use lastPathComponent property of that URL to get the name of the file. Here's an example:

main.swift
// Assuming you have a file named "data.json" in your app's main bundle
guard let fileURL = Bundle.main.url(forResource: "data", withExtension: "json") else {
    print("File not found")
    return
}

let fileName = fileURL.lastPathComponent
print("JSON file name: \(fileName)")
279 chars
9 lines

In this example, we're using Bundle.main to get a reference to our app's main bundle, then using the url(forResource:withExtension:) method to get a reference to our JSON file URL. If the file doesn't exist or cannot be found, we print an error message and return early.

Once we have the file URL, we can get the name of the file by using the lastPathComponent property. This property returns just the file name with its extension, so we don't need to do any further string manipulation. Finally, we print out the name of our JSON file to the console.

gistlibby LogSnag