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.swift279 chars9 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