Confused Confused - 2 months ago 16
Swift Question

Remove suffix from filename in Swift

When trying to remove the suffix from a

filename
, I'm only left with the suffix, which is exactly not what I want.

Here's the scenario, a bunch of files in a texture atlas, in SpriteKit:

fileStructureOfTextureAtlas

I want to get at all the file names of these textures and remove the .png component of their names so that I can tag the subsequent Sprites with these names.

Original Question:
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.




UPDATE:

The first thing I was doing wrong, the most wrong, is that I'd not gotten a clue about the purpose of the 1 at the end of
.map(String.init)[1]


That 1 meant the second part of the string, the bit after the split. That's why png was getting returned.

My fault. I copied the code from part of another, related, answer without understanding it.

After the answers of Nirav D and WMios below, I figured out how to express this for the purposes of looping through these textures:

let myTextureAtlas = SKTextureAtlas(named: "demoArt")
let arrayOfFileNames = myTextureAtlas.textureNames


Nirav D's way:



for name in arrayOfFileNames {
let fileNameWithoutSuffix = name.characters.split(separator: ".").map(String.init).first!
print(fileNameWithoutSuffix)
}


WMios' way:



for name in arrayOfFileNames {
let fileNameWithoutSuffix = name.components(separatedBy: ".").first!
print(fileNameWithoutSuffix)
}

Answer

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

let fileName = "demoArt.png"
let name = fileName.components(separatedBy: ".").first!

To clarify:

fileName.components(separatedBy: ".")

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