Swift
Filepath
Filename Extraction
Programming
Code Tutorial

How to get the filename from the filepath in swift

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Swift, the cleanest way to get a filename from a file path is to treat the path as a file URL and ask for its last path component. That is safer and clearer than manually splitting strings on /. The details matter, though, because a path can represent a file, a directory, or a string that is not actually a filesystem path at all.

Use URL(fileURLWithPath:) and lastPathComponent

For a real local file path, convert it to a file URL and read lastPathComponent.

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

This prints report.pdf. It is the standard answer for normal filesystem paths in Swift.

Get the Filename Without the Extension

If you want just the filename stem, use deletingPathExtension() first.

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

This prints report.

That is usually better than manual string trimming because it lets Foundation handle edge cases around path parsing.

Do Not Use URL(string:) for Local Paths

A very common mistake is using URL(string:) for a filesystem path.

Wrong approach:

swift
let url = URL(string: "/Users/markqian/Documents/report.pdf")

URL(string:) is for URL syntax such as https://example.com/file.txt, not for ordinary local file paths. For local paths, use:

swift
let url = URL(fileURLWithPath: "/Users/markqian/Documents/report.pdf")

Choosing the right initializer prevents subtle parsing bugs.

Directory Paths Behave Differently

If the path points to a directory, lastPathComponent still returns the final path segment.

swift
1import Foundation
2
3let folderPath = "/Users/markqian/Documents/Projects"
4let folderURL = URL(fileURLWithPath: folderPath)
5
6print(folderURL.lastPathComponent)

This prints Projects. That can be useful, but it also means you should know whether the input is supposed to be a file or a directory before using the result semantically.

NSString Also Works, but URL Is Usually Better

Older Cocoa-style code often uses NSString path helpers:

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

This still works and is perfectly valid. In modern Swift, URL(fileURLWithPath:) is often the better default because it composes naturally with other file URL operations such as extension removal, path appending, and existence checks.

Keep Path and URL Semantics Separate

There are three different things people often mix together:

  • a local filesystem path
  • a file URL
  • a web URL

Each one has its own initializer and behavior. If the input came from the file system, treat it as a file path. If it came from a remote service, it may be a URL string instead. Converting everything through the wrong initializer often creates avoidable bugs.

Wrap It in a Helper When Used Often

If filename extraction appears throughout a project, a helper can keep the intent obvious.

swift
1import Foundation
2
3func filename(from path: String) -> String {
4    URL(fileURLWithPath: path).lastPathComponent
5}
6
7print(filename(from: "/tmp/archive.tar.gz"))

If the app also needs the base name without extension, write a second helper explicitly rather than overloading one function with ambiguous behavior.

Common Pitfalls

  • Using URL(string:) for local file paths instead of URL(fileURLWithPath:).
  • Splitting path strings manually on / when Foundation already provides path-aware APIs.
  • Forgetting that lastPathComponent also works for directory paths, not only files.
  • Mixing up the full filename with the filename minus extension.
  • Treating remote URLs and local file paths as if they were parsed the same way.

Summary

  • For local paths in Swift, use URL(fileURLWithPath:) and lastPathComponent.
  • Use deletingPathExtension() if you need the filename without the suffix.
  • Avoid manual string splitting for normal path work.
  • 'NSString path helpers still work, but URL is usually the cleaner modern choice.'
  • Be explicit about whether the input is a local path, a file URL, or a web URL.

Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.