user4592375
user4592375

Reputation:

Weird "fatal error: unexpectedly found nil while unwrapping an Optional value"

I have 6x UIImageView in my ViewController. I also have tap gestures assigned to them. When the user taps an image, segue is performed.

I add those ImageViews to array and that's where an app crashes:

@IBOutlet weak var p0: UIImageView!
@IBOutlet weak var p1: UIImageView!
@IBOutlet weak var p2: UIImageView!
@IBOutlet weak var p3: UIImageView!
@IBOutlet weak var p4: UIImageView!
@IBOutlet weak var p5: UIImageView!

var playlistArray: [UIImageView] = []

override func viewDidLoad() {
    super.viewDidLoad()

    playlistArray += [p0, p1, p2, p3, p4, p5] // App crashes here

    for index in 0..<playlistArray.count {
        let playlist = Playlist(index: index)
        let playlistImageView = playlistArray[index]

        playlistImageView.image = playlist.icon
        playlistImageView.backgroundColor = playlist.backgroundColor
    }
}

I am getting an error:

fatal error: unexpectedly found nil while unwrapping an Optional value

What am I doing wrong? All the ImageViews are connected.

Mind you, I am following a tutorial where the code is practically the same, hence the method of adding ImageView to an array - it's a beginner course.

I've set a breakpoints and I am sure none of the ImageViews is nil.
They are all properly connected.

Edit:

I've uploaded my project. If anyone has a moment, I would appreciate looking what might be wrong there: https://www.dropbox.com/s/fj0tgi9st2xr7y5/s_PlaylistBrowser.zip?dl=0

Upvotes: 0

Views: 409

Answers (2)

gnasher729
gnasher729

Reputation: 52632

You wrote: "What am I doing wrong? All the ImageViews are connected."

That's a beginner's mistake. There is a problem, and you assume that you did everything right. But it should be common sense that you did not do everything right - if you did, your code would work!

The question that you should ask yourself automatically is: I did something wrong. What did I wrong? If you asked yourself that question, then it would be obvious with the point of the crash and the error message that one of p0, p1, p2, p3, p4 or p5 is nil.

Upvotes: 1

Fengson
Fengson

Reputation: 4912

I've looked at your code.
Basically, you missed a label connection in DetailsViewController.
Because of that program would crash only when you try to perform a segue.
I don't know why it pointed at the line you mentioned, though.

Upvotes: 1

Related Questions