0

I'm working on a Swift project and I keep getting this error: "Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value" on this block of code:

func addPicture(pic: Picture!){
    pictureArray.append(pic)
}

(Note: I've tried it both as pic: Picture and pic: Picture! and I get the same error either way)

pictureArray is defined as such:

    var pictureArray: [Picture]!

I get this error when I'm trying to save the picture and pop the current VC:

@objc func dismissViewControllerAndSave() {
    let picture = Picture(name: "NewPic", preview: "newpic", colorDictionary: [:], blueprint: [])
    let viewController = ViewController()
    viewController.addPicture(pic: picture)
    self.navigationController?.popViewController(animated: true)
}

I've been working on trying to fix this issue for a long time and I'm not sure how to resolve it. picture isn't an optional value so I have no clue why I keep getting this error. I'd really appreciate any type of help I could get. Thanks!

ineedhelp
  • 31
  • 4
  • 1
    Change picture array like so `var pictureArray: [Picture] = [Picture]()`, as it is nil the first time you call this and with `!` you can't check for nils on it – zaitsman Aug 10 '20 at 00:40
  • I don't consider this an exact duplicate (and while I suspect there is one, I haven't found it so far), but you should also read https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu – Rob Napier Aug 10 '20 at 00:57

1 Answers1

3

A ! type is an implicitly unwrapped optional (IUO). It means that the value is technically Optional, but it is a programming error for it to be read if it is nil.

As a rule, you don't need IUOs. There are a few corner cases where they come up around initialization ordering, and they used to be necessary to deal with unannotated Objective-C bridging. But most of the time you don't need them, and you definitely don't need to pass a Picture! as a parameter (I can't think of any case where that would make sense).

Remove the !.

func addPicture(pic: Picture){
    pictureArray.append(pic)
}

var pictureArray: [Picture]

When you do that, you'll probably get an error that pictureArray isn't initialized. That's good. That error is telling you where you've made your mistake. You probably just want to initialize it when you define it in this case:

var pictureArray: [Picture] = []

You could also initialize it in init.

For more information on IUOs, see "Implicitly Unwrapped Optionals" in the Swift Programming Language. For the common corner case where they actually are useful, see Unowned References and Implicitly Unwrapped Optional Properties.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610