在解包Optional值时,HTHorizo​​ntalSelectionList意外地发现了nil

时间:2015-01-27 04:59:11

标签: swift

..我会告诉你原因:

我正在使用以下广告连播:HTHorizontalSelectionList

如果我这样声明:

class RightViewController: UIViewController, HTHorizontalSelectionListDelegate, HTHorizontalSelectionListDataSource {

    var selectionList: HTHorizontalSelectionList!
}

我在编译时遇到以下错误:

ld: warning: directory not found for option '-FTest'
Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_HTHorizontalSelectionList", referenced from:
      __TMaCSo25HTHorizontalSelectionList in RightViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

咦!? 什么的!?

如果我改为像这样实现它编译好了!

override func viewDidLoad() {
    super.viewDidLoad()

    var selectionList: HTHorizontalSelectionList!
    selectionList?.frame = CGRectMake(0, 0, self.view.frame.size.width, 40)
    selectionList?.delegate = self
    selectionList?.dataSource = self
    self.view.addSubview(selectionList)
}

...当然,我在addSubview行上收到错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

当我经常发生这样的事情时,我发现很难理解Swift是如何工作的。

1 个答案:

答案 0 :(得分:1)

  

我发现当我经常发生这样的事情时,我很难理解Swift是如何工作的

这没什么难的。您开始时将Optional变量设置为nil。它保持nil。最终你试图打开nil,然后崩溃,因为你不能这样做:

var selectionList: HTHorizontalSelectionList! // it is nil
selectionList?.frame = CGRectMake(0, 0, self.view.frame.size.width, 40) // still nil, nothing happens
selectionList?.delegate = self // still nil, nothing happens
selectionList?.dataSource = self // still nil, nothing happens
self.view.addSubview(selectionList) // unwrap, crash

如果您不想崩溃,请为selectionList分配nil以外的实际值,例如可能是实际的HTHorizo​​ntalSelectionList。