Llg Llg - 18 days ago 8
Swift Question

Swift: “unexpectedly found nil while unwrapping an Optional value” in array append

Trying to make a loader using animation trough this code:

var images: [UIImage] = []
for i in 1...10
{
let strImageName : String = "loader\(i).png"
images.append(UIImage(named: strImageName)!)
}
self.loader.animationImages = images
self.loader.animationDuration = 1.0
self.loader.startAnimating()


I got this error fatal error: "unexpectedly found nil while unwrapping an Optional value
Then my application crashed" and those information from the debugger after the crash:

images = ([UImage]) 0 values
strImageName = (String) “loader1.png”


I can’t understand what is wrong in my code.
Can anyone help me please?

Answer

What's happening is that UIImage's initializer is failable and the image you're trying to create can't be found so force unwrapping crashes. You have to conditionally unwrap (i.e. if let):

var images: [UIImage] = []
for i in 1...10  {
    let strImageName = "loader\(i).png"
    if let image = UIImage(named: strImageName) {
        images.append(image)
    } else {
        print("Image '\(strImageName)' does not exist!")
    }
}
self.loader.animationImages = images
self.loader.animationDuration = 1.0
self.loader.startAnimating()

You can also do it in a single line using map/flatMap:

let images = (1...10).map { "loader\($0).png" }.map { UIImage(named: $0) }.flatMap { $0 }