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.
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.
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.
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:
URL(string:) is for URL syntax such as https://example.com/file.txt, not for ordinary local file paths. For local paths, use:
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.
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:
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.
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 ofURL(fileURLWithPath:). - Splitting path strings manually on
/when Foundation already provides path-aware APIs. - Forgetting that
lastPathComponentalso 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:)andlastPathComponent. - Use
deletingPathExtension()if you need the filename without the suffix. - Avoid manual string splitting for normal path work.
- '
NSStringpath helpers still work, butURLis usually the cleaner modern choice.' - Be explicit about whether the input is a local path, a file URL, or a web URL.
Related reading
- How to get the filename from the filepath in swift
- How to get the hour of the day with Swift?
- How to get the hour of the day with Swift?
- How to get the indexpath.row when an element is activated?
- How to get the indexpath.row when an element is activated?
- How to get the iPhone's screen width in SwiftUI?
- How to get the name of enumeration value in Swift?
- How to get the name of the running application in iOS
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.