Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Wednesday, December 30, 2015

How to split filename from file extension in Swift?

How to split filename from file extension in Swift?


Given the name of a file in the bundle, I want load the file into my Swift app. So I need to use this method:

let soundURL = NSBundle.mainBundle().URLForResource(fname, withExtension: ext)  

For whatever reason, the method needs the filename separated from the file extension. Fine, it's easy enough to separate the two in most languages. But so far I'm not finding it to be so in Swift.

So here is what I have:

var rt: String.Index = fileName.rangeOfString(".", options:NSStringCompareOptions.BackwardsSearch)  var fname: String = fileName .substringToIndex(rt)  var ext = fileName.substringFromIndex(rt)  

If I don't include the typing on the first line, I get errors on the two subsequent lines. With it, I'm getting an error on the first line:

Cannot convert the expression's type '(UnicodeScalarLiteralConvertible, options: NSStringCompareOptions)' to type 'UnicodeScalarLiteralConvertible'  

How can I split the filename from the extension? Is there some elegant way to do this?

I was all excited about Swift because it seemed like a much more elegant language than Objective C. But now I'm finding that it has its own cumbersomeness.


Second attempt: I decided to make my own string-search method:

func rfind(haystack: String, needle: Character) -> Int {      var a = Array(haystack)        for var i = a.count - 1; i >= 0; i-- {          println(a[i])          if a[i] == needle {              println(i)              return i;          }      }      return -1  }  

But now I get an error on the line var rt: String.Index = rfind(fileName, needle: "."):

'Int' is not convertible to 'String.Index'  

Without the cast, I get an error on the two subsequent lines.

Can anyone help me to split this filename and extension?

Answer by Mike S for How to split filename from file extension in Swift?


Strings in Swift can definitely by tricky. If you want a pure Swift method, here's how I would do it:

  1. Use find to find the last occurrence of a "." in the reverse of the string
  2. Use advance to get the correct index of the "." in the original string
  3. Use String's subscript function that takes an IntervalType to get the strings
  4. Package this all up in a function that returns an optional tuple of the name and extension

Something like this:

func splitFilename(str: String) -> (name: String, ext: String)? {      if let rDotIdx = find(reverse(str), ".") {          let dotIdx = advance(str.endIndex, -rDotIdx)          let fname = str[str.startIndex..

Which would be used like:

let str = "/Users/me/Documents/Something.something/text.txt"  if let split = splitFilename(str) {      println(split.name)      println(split.ext)  }  

Which outputs:

/Users/me/Documents/Something.something/text  txt  

Or, just use the already available NSString methods like pathExtension and stringByDeletingPathExtension.

Answer by gabbler for How to split filename from file extension in Swift?


As pointed out in the comment, you can use this.

let filename: String = "bottom_bar.png"  let pathExtention = filename.pathExtension  let pathPrefix = filename.stringByDeletingPathExtension  

Answer by Derek Knight for How to split filename from file extension in Swift?


A better way (or at least an alternative in Swift 2.0) is to use the String pathComponents property. This splits the pathname into an array of strings. e.g

if let pathComponents = filePath.pathComponents {      if let last = pathComponents.last {          print(" The last component is \(last)") // This would be the extension          // Getting the last but one component is a bit harder          // Note the edge case of a string with no delimiters!      }  }  // Otherwise you're out of luck, this wasn't a path name!  

Answer by Julian for How to split filename from file extension in Swift?


This is with Swift 2, Xcode 7: If you have the filename with the extension already on it, then you can pass the full filename in as the first parameter and a blank string as the second parameter:

let soundURL = NSBundle.mainBundle()      .URLForResource("soundfile.ext", withExtension: "")  

Alternatively nil as the extension parameter also works.

If you have a URL, and you want to get the name of the file itself for some reason, then you can do this:

soundURL.URLByDeletingPathExtension?.lastPathComponent  

Answer by Defide Tester Defide for How to split filename from file extension in Swift?


In Swift , you can change to NSString to get extension , it faster:

extension String{      func getPathExtension() -> String{          return (self as NSString).pathExtension      }  }  

Answer by Santanu Karar for How to split filename from file extension in Swift?


In Swift 2.1 String.pathExtension is not available anymore. Instead you need to determine it through NSURL conversion:

NSURL(fileURLWithPath: filePath).pathExtension  

Answer by Aneel for How to split filename from file extension in Swift?


In Swift 2.1, it seems that the current way to do this is:

let filename = fileURL.URLByDeletingPathExtension?.lastPathComponent  let extension = fileURL.pathExtension  

Answer by Pescolly for How to split filename from file extension in Swift?


They got rid of pathExtension for whatever reason.

let str = "Hello/this/is/a/filepath/file.ext"  let l = str.componentsSeparatedByString("/")  let file = l.last?.componentsSeparatedByString(".")[0]  let ext = l.last?.componentsSeparatedByString(".")[1]  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.