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]()
或添加一行对其进行初始化,如果您想将其设置为可选的话。