Swift
Filename Extraction
Filepath Handling
Swift Programming
iOS Development

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 safest way to extract a filename from a path is usually to treat the path as a file URL rather than manually splitting the string. That gives you access to lastPathComponent, pathExtension, and related APIs that already handle path separators and common edge cases correctly.

Use URL(fileURLWithPath:) for Local Paths

If the input is a filesystem path, create a file URL and read its 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 most idiomatic solution in modern Swift because it works with the Foundation path APIs instead of relying on brittle string slicing.

The important detail is using fileURLWithPath: rather than URL(string:). URL(string:) is for URL syntax such as https://example.com/file.txt. A local path such as /Users/mark/file.txt should be handled as a file path.

Remove the Extension When Needed

Sometimes the real requirement is not “filename” but “filename without extension.” In that case, 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 is preferable to manually splitting on . because filenames can contain more than one dot.

Extract the Extension Separately

If you need the extension itself, pathExtension is already available.

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

This behavior is often what you want, but notice that only the final extension is returned. If your application needs to detect compound endings such as tar.gz, you should define that rule explicitly instead of assuming the API will do it for you.

NSString Also Works

Older Swift codebases sometimes use NSString path helpers. They still work and can be useful when maintaining Objective-C-heavy projects.

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

This is valid, but new Swift code should usually prefer URL because the API is more clearly designed around file locations and path manipulation.

Handle Trailing Slashes Carefully

A path ending with a trailing slash may describe a directory rather than a file.

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

That result is correct for the last path component, but it may not represent a filename in the semantic sense. If your function should only accept files, you may need an additional check using FileManager.

A Small Reusable Helper

Wrapping the behavior in one helper makes calling code clearer.

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 like this also gives you one place to add validation if the project later distinguishes between files, directories, or invalid inputs.

Why Manual String Splitting Is Weak

You can split on / and grab the last segment, but it is usually a poor default.

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

That may work in simple cases, but it does not communicate intent as clearly as the Foundation path API, and it becomes more error-prone once you deal with edge cases such as empty input, trailing separators, or URL-like strings.

Common Pitfalls

  • 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.

Summary

  • For local paths in Swift, use URL(fileURLWithPath:).
  • Read the filename with lastPathComponent.
  • Use deletingPathExtension() when you need the stem without the extension.
  • 'NSString path helpers still work, but URL is usually the better default in modern Swift.'
  • Avoid manual string splitting unless you have a very specific reason.

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.