Swift
Filename Extraction
Filepath Handling
Swift Programming
iOS Development

Get the filename from a file path in Swift with lastPathComponent

Codemia Knowledge Hub ·

Turn the path into a file URL with URL(fileURLWithPath:) and read its lastPathComponent. Foundation's URL APIs, including pathExtension and deletingPathExtension(), already handle path separators and common edge cases, so you do not need to split the string yourself.

URL(fileURLWithPath:) and lastPathComponent

swift
1import Foundation
2
3let path = "/Users/mark/Documents/report.pdf"
4let url = URL(fileURLWithPath: path)
5
6print(url.lastPathComponent)  // report.pdf

This is the idiomatic approach in modern Swift. Use fileURLWithPath:, not URL(string:). URL(string:) is for URL syntax such as https://example.com/file.txt, while a local path such as /Users/mark/file.txt should be handled as a file path.

Filename without the extension

Use deletingPathExtension():

swift
1import Foundation
2
3let path = "/Users/mark/Documents/report.pdf"
4let url = URL(fileURLWithPath: path)
5
6let filename = url.lastPathComponent
7let stem = url.deletingPathExtension().lastPathComponent
8
9print(filename)  // report.pdf
10print(stem)      // report

This beats splitting on ., because filenames can contain more than one dot.

Just the extension

pathExtension returns it directly:

swift
1import Foundation
2
3let path = "/Users/mark/Documents/archive.tar.gz"
4let url = URL(fileURLWithPath: path)
5
6print(url.lastPathComponent)  // archive.tar.gz
7print(url.pathExtension)      // gz

Only the final extension is returned. If your app needs to detect compound endings such as tar.gz, define that rule explicitly.

NSString path helpers

Older codebases, especially Objective-C-heavy ones, often use NSString helpers. They still work:

swift
1import Foundation
2
3let path = "/Users/mark/Documents/report.pdf" as NSString
4print(path.lastPathComponent)    // report.pdf
5print(path.deletingPathExtension) // /Users/mark/Documents/report

For new Swift code, prefer URL, whose API is designed around file locations.

Trailing slashes and directories

A path ending in a slash may describe a directory:

swift
1import Foundation
2
3let directoryPath = "/Users/mark/Documents/"
4let url = URL(fileURLWithPath: directoryPath)
5
6print(url.lastPathComponent)  // Documents

That is the correct last path component, but it is not a filename. If your function should only accept files, add a check with FileManager.

A reusable helper

swift
1import Foundation
2
3func filename(from path: String) -> String {
4    URL(fileURLWithPath: path).lastPathComponent
5}
6
7func filenameWithoutExtension(from path: String) -> String {
8    URL(fileURLWithPath: path)
9        .deletingPathExtension()
10        .lastPathComponent
11}
12
13print(filename(from: "/tmp/image.png"))
14print(filenameWithoutExtension(from: "/tmp/image.png"))

A helper also gives you one place to add validation later, for example to distinguish files, directories and invalid input.

Why not split the string on /

You can grab the last segment after splitting:

swift
let path = "/Users/mark/Documents/report.pdf"
let pieces = path.split(separator: "/")
print(pieces.last ?? "")

It works in simple cases, but it states intent less clearly than the Foundation API and gets error-prone with empty input, trailing separators or URL-like strings.

Mistakes to avoid

  • Using URL(string:) for a local file path instead of URL(fileURLWithPath:).
  • Splitting the path manually when lastPathComponent already exists.
  • Assuming the last path component is always a file rather than possibly a directory.
  • Removing the extension by splitting on . instead of using deletingPathExtension().
  • Forgetting that pathExtension returns only the final extension segment.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms