Skip to content

Getting a URL's Filename in Swift

Swift, URL, Filename1 min read

URLs are an integral part of modern programming, serving as references to resources on the web or local systems. In many cases, developers need to work with URLs and extract specific components from them. One common task is extracting the filename from a given URL. In this article, we will explore how to achieve this using Swift. We'll delve into different methods and provide practical examples to help you grasp this concept effectively.

Understanding the Problem

When working with URLs, it's crucial to be able to extract specific parts such as the filename. Given a URL pointing to a file, being able to isolate the filename becomes essential for various operations within an application. Fortunately, Swift provides us with the necessary tools to accomplish this task seamlessly.

Using URL.lastPathComponent

One straightforward approach to obtaining the filename from a URL in Swift is by utilizing the lastPathComponent property provided by the URL type. This property returns the last portion of the URL path. Let's take a look at an example:

1let fileURL = URL(string: "")!
2let filename = fileURL.lastPathComponent
3print(filename) // Output: document.pdf

In the above example, given the URL "", the lastPathComponent property efficiently retrieves the filename "document.pdf" from the URL.

Extracting Filename Without File Extension

At times, there might be a need to retrieve the filename without its extension. Swift enables us to achieve this by manipulating the result obtained from lastPathComponent. We can use standard string manipulation techniques to obtain the filename without its extension. Here's how it can be done:

1let fullFilename = fileURL.lastPathComponent
2if let dotIndex = fullFilename.firstIndex(of: ".") {
3 let filenameWithoutExtension = fullFilename[..<dotIndex]
4 print(filenameWithoutExtension) // Output: document

In this code snippet, we first obtain the full filename using lastPathComponent, and then we locate the position of the file extension separator (in this case, the period). With that information, we extract the substring before the dot, resulting in the filename "document".