Home > Mobile >  Problems with Optionals
Problems with Optionals

Time:05-27

I started learning Swift on my own from books and a tutorial from YouTube. And when I tried to repeat over the video, I got the error

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"`

In the cycle for I in

What is the problem here?

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var collectionViwe: UICollectionView!
    
    var imagesUIImages = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionViwe.dataSource = self
        collectionViwe.delegate = self
        
        for i in 0...7 {
            let image = UIImage(named: "image \(i)")! 
            imagesUIImages.append(image)
        }
    }
}

CodePudding user response:

You probably have only seven images and not eight, but you count to eight. The range 0...7 counts to seven, including seven. If you only have seven images, you should count to six, for instance 0..<7 or 0...6.

If you indeed only have seven images, then the image "image 7" doesn't exist and, since you are force unwrapping it with an !, your app crashes.

Please, try:

for i in 0..<7 {
    let image = UIImage(named: "image \(i)")! 
    imagesUIImages.append(image)
}

Kind regards, MacUserT

CodePudding user response:

As MacUserT suggests, you probably have 7 images instead of 8. I would like to add to his answer that it would be wise and a good practice to unwrap the optional first and if you have a value then it will be added to the list of images.

So the code would be,

for i in 0..<7 {
    if let image = UIImage(named: "image \(i)") {
        imagesUIImages.append(image)
    }
}
  • Related