user979331 user979331 - 4 months ago 5
iOS Question

Swift - unexpectedly found nil while unwrapping an Optional value when adding item to array

I have an array like so:

var gestureArray: Array<UIGestureRecognizer>!


and I am trying to add item to this array like so:

for gesture in webview.scrollView.gestureRecognizers!
{
gestureArray.insert(gesture, atIndex: 0)
}

print(gestureArray)


but I get this error after attempting to add the first item:

unexpectedly found nil while unwrapping an Optional value


When I print each gesture they look like this:

<UIScrollViewDelayedTouchesBeganGestureRecognizer: 0x124eabb60; state = Possible; delaysTouchesBegan = YES; view = <_UIWebViewScrollView 0x125825400>; target= <(action=delayed:, target=<_UIWebViewScrollView 0x125825400>)>>

<UIScrollViewPanGestureRecognizer: 0x124eac370; state = Possible; delaysTouchesEnded = NO; view = <_UIWebViewScrollView 0x125825400>; target= <(action=handlePan:, target=<_UIWebViewScrollView 0x125825400>)>>

<UIScrollViewPinchGestureRecognizer: 0x124d892a0; state = Possible; delaysTouchesEnded = NO; view = <_UIWebViewScrollView 0x125825400>; target= <(action=handlePinch:, target=<_UIWebViewScrollView 0x125825400>)>>

Answer

This means that the array has not been initialized to a non-nil value.

When you put exclamation point ! after a type, you tell Swift two things:

  • It is perfectly legal for the value of gestureArray to be nil, and
  • You are going to assign a non-nil value to gestureArray prior to accessing it.

In return Swift lets you access gestureArray as if it were not optional (i.e. with gestureArray.insert(...) instead of gestureArray!.insert(...))

From the exception that you are getting it appears that gestureArray is still nil when you call insert on it.

Comments