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 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.
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().
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.
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.
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.
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.
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.
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 ofURL(fileURLWithPath:). - Splitting the path manually when
lastPathComponentalready exists. - Assuming the last path component is always a file rather than possibly a directory.
- Removing the extension by splitting on
.instead of usingdeletingPathExtension(). - Forgetting that
pathExtensionreturns 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. - '
NSStringpath helpers still work, butURLis usually the better default in modern Swift.' - Avoid manual string splitting unless you have a very specific reason.
Related reading
- 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
- How to get the Power of some Integer in Swift language?
.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.