[SOLVED] Remove suffix from filename in Swift

Issue

When trying to remove the suffix from a filename, I’m only left with the suffix, which is exactly not what I want.

What (how many things) am I doing wrong here:

let myTextureAtlas = SKTextureAtlas(named: "demoArt")

let filename = (myTextureAtlas.textureNames.first?.characters.split{$0 == "."}.map(String.init)[1].replacingOccurrences(of: "\'", with: ""))! as String

print(filename)

This prints png which is the most dull part of the whole thing.

Solution

You can also split the String using componentsSeparatedBy, like this:

let fileName = "demoArt.png"
var components = fileName.components(separatedBy: ".")
if components.count > 1 { // If there is a file extension
  components.removeLast()
  return components.joined(separator: ".")
} else {
  return fileName
}

To clarify:

fileName.components(separatedBy: ".")

will return an array made up of "demoArt" and "png".

Answered By – Wyetro

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *