【问题标题】:unexpectedly found nil in swift在swift中意外发现nil
【发布时间】:2014-10-31 19:01:34
【问题描述】:

我的控制器中有这样的代码:

var itemList:[String] = []

@IBOutlet var tasksTable:UITableView!

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return itemList.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

    cell.textLabel.text = itemList[indexPath.row]

    return cell
}

override func viewWillAppear(animated: Bool) {
    tasksTable.reloadData() <-----------------------
}

为什么会出现这个错误?

错误:在展开可选值时意外发现 nil

【问题讨论】:

    标签: ios iphone swift


    【解决方案1】:

    这是因为此时viewWillAppear被调用,tasksTable为nil。你可能忘记在笔尖上连接插座了。

    【讨论】:

    • 我已经连接了插座。但是,最初数组将为 nil。有没有办法处理 nil 数组?
    • 这实际上是 Swift 的一个非常好的特性。如果这发生在 Objective-C 中,什么都不会发生;你的表格视图不起作用,但你不知道为什么。这样一来,斯威夫特就会因为你没有连接插座而扇你一巴掌。
    • 不,数组 (itemList) 永远不会为零。不是您编写代码的方式。它可以为空,但永远不能为零。同样,这是一个非常棒的 Swift 功能。
    猜你喜欢
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 2020-08-26
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2014-09-10
    相关资源
    最近更新 更多