Search code examples
xcodeswiftanimatedleading-zerozero-pad

Looping zero-padded numbers in swift - Xcode


Under the SKSpriteNode class, you can do the following to animate an object

private func animate(){
  var playerTextures:[SKTexture] = []
  for i in 1...3 {
    playerTextures.append(SKTexture(imageNamed: "image00\(i)"))
  }
  let playerAnimation = SKAction.repeatActionForever(
    SKAction.animateWithTextures(playerTextures, timePerFrame: 0.1))
  self.runAction(playerAnimation)
}

The above code can animate an object using the sequence of images. Here the image files would be image001.png image002.png image003.png

Here come's my question, how can I animate images if the file names are image001.png image002.png ... image009.png image010.png image011.png image012.png The key point here is the problem with the zero paddings. Any ideas?


Solution

  • Assuming you will only have three digits number you could add your pictures that way:

    for i in 1...3 {
        let imageNumber = String(format: "%03d", i)
        playerTextures.append(SKTexture(imageNamed: "image\(imageNumber)"))
    }
    

    This will give you image001, image002 and image003

    This requires that you import Foundation at the beginning of your swift file