Reputation: 1550
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?
Upvotes: 0
Views: 1291
Reputation: 17
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.
Upvotes: 0
Reputation: 7564
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 }
Upvotes: 2
Reputation: 9226
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)
}
Upvotes: 1