How to get the filename from the filepath in swift

Swift 2:

var file_name = NSURL(fileURLWithPath: path_to_file).lastPathComponent!

SWIFT 3.x or SWIFT 4: Shortest and cleanest way of doing this is below. In this example url variable is type of URL in this way we can have a human readable String result of the full file name with extension like My file name.txt and Not like My%20file%20name.txt

// Result like: My file name.txt
let fileName = url.lastPathComponent

If you want to get the current file name such as for logging purposes, I use this.

Swift 4

URL(fileURLWithPath: #file).lastPathComponent

Objective C

NSString* theFileName = [string lastPathComponent]

Swift

let theFileName = (string as NSString).lastPathComponent

Tags:

Ios

Iphone

Swift