user6567889 user6567889 - 11 months ago 30
Swift Question

How to remove this EXC_BAD Access error?

My code:

override func viewDidLoad()
imagePicker.delegate = self
myScrollView.delegate = self
myScrollView.subviews.forEach({ $0.removeFromSuperview() })

for i in 1...2
myView = UIView(frame:CGRectMake(myView.frame.origin.x,22.0,320,83))
myView.tag = i
myScrollView.contentSize = CGSizeMake(myScrollView.frame.size.width*2,128.0)

The error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Rob Rob
  1. This line is probably not correct:

     myView = UIView(frame:CGRectMake(myView.frame.origin.x,22.0,320,83))

    You are using myView in the same line in which you instantiate it. If you examine myView before this line is called, it is likely nil.

  2. Most likely myScrollView or imagePicker is an implicitly wrapped optional @IBOutlet that is nil. Examine these values before using them (either by inserting print statement, or by adding breakpoint and then examining the values in the debugger). See if either of these are nil.

    In terms of why it might be nil, the two most common problems are:

    • The outlet can be nil if you neglected to hook the @IBOutlet in Interface Builder. This can be confirmed by checking the outlets for the scroll view in IB. It can also be quickly confirmed by seeing if the outlet connector in the left margin next to the outlet


      enter image description here

      Not connected:

      enter image description here


    • You can also have outlets be nil if transitioning to this scene programmatically, but doing so incorrectly (i.e. instantiating this scene from the class rather than from the storyboard).