Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine filetype of path string in Swift

Tags:

ios

swift

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.

like image 560
Shaik MD Ashiq Avatar asked Jul 09 '15 02:07

Shaik MD Ashiq


3 Answers

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

like image 103
Ashish Kakkad Avatar answered Nov 12 '22 07:11

Ashish Kakkad


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
like image 21
Crashalot Avatar answered Nov 12 '22 07:11

Crashalot


let filename: String = "test.pdf"
let pathExtention = filename.pathExtension
like image 6
Hayley Guillou Avatar answered Nov 12 '22 07:11

Hayley Guillou