I need to decide the filetype of a file from the filename which I get in string. So I decided to get the last three characters of the String to decide what filetype it is. How do I get the last three characters in a String. For example
var fileName = "test.pdf"
I need to get the pdf alone. Is there any other better way to check for the file type other than this. Please suggest me that also. Because I think, I won be able to recognise if the filetype comes in four characters like "jpeg" and other stuff. Thanks in advance.
I think you are looking for :
The path extension, if any, of the string as interpreted as a path. (read-only) Declaration
Swift
var pathExtension: String { get }
Discussion
The path extension is the portion of the last path component which follows the final period, if there is one. The extension divider is not included. The following table illustrates the effect of pathExtension
on a variety of different paths:
Receiver’s String Value
String Returned
“/tmp/scratch.tiff” “tiff”
Example :
file.pathExtension
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/occ/instm/NSString/pathExtension
As of Swift 2.x, pathExtension
is no longer available for the String
class.
You can instead cast to NSString
and do:
let filename = "test.pdf"
let extension = (filename as NSString).pathExtension
let filename: String = "test.pdf"
let pathExtention = filename.pathExtension
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With