0

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?

3

3 Answers 3

2

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 }
Sign up to request clarification or add additional context in comments.

1 Comment

(1...10).map without casting to Array will work too.
1

You need to use if let construct for safely unwrap because UIImage's initializer is failable.

public /*not inherited*/ init?(named name: String)

The named of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.

Return Value - The image object for the specified file, or nil if the method could not find the specified image.

let strImageName = "loader\(i).png"

if let image = UIImage(named: strImageName) {
    images.append(image)
}

Comments

0

Apple's Swift Guide : Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.

1 Comment

Except that OP is not using an implicitly unwrapped Optional, they are just force unwrapping a normal Optional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.