0

I've got this properly working map function:

let movingImages = (1...71).map { UIImage(named: "Animation.\($0)")! }

Except there is no Animation.1 file - it's Animation.01

Rather than renaming the files, how can I code it to add a 0 to the numbers before 10?

Edit: this question differs from others because the answer provided elsewhere about adding a 0 to single digit number in Swift needs additional context in order to be used within a mapping that needs to return a value

RanLearns
  • 4,086
  • 5
  • 44
  • 81

1 Answers1

2

You can use the String(format: ...) with the %02d for this:

let movingImages = (1...71).map {  index -> UIImage? in
     let imageNumber = String(format: "%02d", index) 
     return UIImage(named: "Animation.\(imageNumber)")!
}

Also, on the side note, avoid using force unwrapping (!).

A more safe way:

Swift 4:

let movingImages = (1...71).flatMap { index -> UIImage? in
     let imageNumber = String(format: "%02d", index) 
     return UIImage(named: "Animation.\(imageNumber)")
}

Swift 4.1:

let movingImages = (1...71).compactMap { index -> UIImage? in
     let imageNumber = String(format: "%02d", index) 
     return UIImage(named: "Animation.\(imageNumber)")
}
Dejan Skledar
  • 11,280
  • 7
  • 44
  • 70
  • 1
    Forced unwrapping of the images is actually desired here since it will cause a crash letting the developer know very early in development that there is a missing image file. The use of `flatMap/compactMap` will hide the fact that one or more of the images may be missing. – rmaddy May 14 '18 at 14:43