Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/115.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift-在将项添加到数组时展开可选值时意外发现nil_Ios_Arrays_Swift - Fatal编程技术网

Ios Swift-在将项添加到数组时展开可选值时意外发现nil

Ios Swift-在将项添加到数组时展开可选值时意外发现nil,ios,arrays,swift,Ios,Arrays,Swift,我有这样一个数组: var gestureArray: Array<UIGestureRecognizer>! for gesture in webview.scrollView.gestureRecognizers! { gestureArray.insert(gesture, atIndex: 0) } print(gestureArray) 但我在尝试添加第一项后出现此错误: unexpectedly

我有这样一个数组:

var gestureArray: Array<UIGestureRecognizer>!
for gesture in webview.scrollView.gestureRecognizers!
        {
            gestureArray.insert(gesture, atIndex: 0)
        }

        print(gestureArray)
但我在尝试添加第一项后出现此错误:

unexpectedly found nil while unwrapping an Optional value
当我打印每个手势时,它们看起来像这样:

<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>)>>

这意味着数组尚未初始化为非零值

当你把感叹号
键入后,您告诉Swift两件事:

  • gestureArray
    的值为
    nil
    是完全合法的,并且
  • 在访问
    gestureArray
    之前,您将为其分配一个非nil值
作为回报,Swift允许您访问
gestureArray
,就像它不是可选的一样(即使用
gestureArray.insert(…)
而不是
gestureArray!.insert(…)


从您得到的异常情况来看,当您调用
insert
时,
gestureArray
仍然是
nil

您的
gestureArray
值为nil。可以通过以下方式创建变量:

var gestureArray=[UIgestureRecognitor]()



您正在创建一个变量并设置它的类型,但它的值从未被赋值。还有另一个错误,就是您不能创建一个类属性并将其设置为
未包装可选的
。您应该始终或创建一个变量并为其赋值,或将其类型设置为
可选
。例如:
var gestureArray:[uigesturecognizer]?

您能给我一个我应该做什么的例子吗?@user979331根据您的要求,您可以将
gestureArray
设置为非可选,即
var gestureArray=[uigesturecognizer]()
或添加一行对其进行初始化,如果您想将其设置为可选的话。