Dani
Dani

Reputation: 3637

Nil while unwrapping an optional that actually has a value

I'm getting a very weird error, while unwrapping an optional. When I print the value, I can actually see it but yet, it crashes and it says:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

Here's the code (fetchPost() is called in the viewDidLoad():

func fetchPost() {
    Api.Posts.observePostIncludingImages(withId: postId) { (post, photosStringArray) in

        self.isLiked(postId: post.id!, completion: { boolValue in
            Api.Posts.fetchCount(postId: post.id!, completion: { totalCount in
                post.isLiked = boolValue

                self.photosArrayString = photosStringArray
                print(photosStringArray) // prints the actual image string
                self.setScrollView()

            })
        })
    }
}

func setScrollView() {
    for  i in stride(from: 0, to: photosArrayString.count, by: 1) {
        var frame = CGRect.zero
        frame.origin.x = self.galleryScrollView.frame.size.width * CGFloat(i)
        frame.origin.y = 0
        frame.size = self.galleryScrollView.frame.size
        galleryScrollView.isPagingEnabled = true

        let newUIImageView = UIImageView()
        print(photosArrayString[i]) // Prints the value again
        let myImage = UIImage(named: photosArrayString[i])! // CRASHES! i = 0 (first item in the array)

        avgBackgroundColorsOfImage.append(myImage.averageColor!)

        newUIImageView.image = myImage
        newUIImageView.frame =  frame

        newUIImageView.contentMode = UIViewContentMode.scaleAspectFit

        newUIImageView.sd_setImage(with: URL(string: self.photosArrayString[i]), completed: nil)


        galleryScrollView.backgroundColor = avgBackgroundColorsOfImage[i]
        galleryScrollView.addSubview(newUIImageView)

        self.galleryScrollView.contentSize = CGSize(width: self.galleryScrollView.frame.size.width * CGFloat(photosArrayString.count),
                                                    height: self.galleryScrollView.frame.size.height)
        pageControl.addTarget(self, action: #selector(changePage), for: UIControlEvents.valueChanged)
    }
}

Upvotes: 1

Views: 57

Answers (1)

Connor Neville
Connor Neville

Reputation: 7361

The thing you are unwrapping is the optional UIImage you just created. Whatever string is being held in the array is a valid string. It is not, however, the name of a valid image in your asset catalog. Note the error is about "unwrapping a nil value", not "array out of bounds" - these are different things.

The docs on this initializer show how it's an optional init that returns "the image object for the specified file, or nil if the method could not find the specified image."

Upvotes: 3

Related Questions