..我会告诉你为什么:
我正在使用以下 pod: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 是如何工作的。
我发现当我经常遇到这样的事情时,很难理解 Swift 是如何工作的。
这没有什么难的。您开始时将可选变量设置为 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
以外的实际值,例如实际的 HTHorizontalSelectionList。